I dont understand something

Hello.Some one explain me why im thinking wrong with this code?

in this line CombatTarget target = hit.transform.GetComponent();
why i have to access the transform and then GetComponent<>() ?
Why is not working the code this way:
CombatTarget target = hit.GetComponent(); ?
Why i cant skip the hit.transform? In my head we acces the hit variable. Then we want to get acces to combat target component. I dont understand the transform acces here.

Thank you.

The variable hit is of the struct type RaycastHit. It is not itself the game object that was hit, but rather a data structure that gives you some info about said game object and how the ray hit it. There is no GetComponent() in RaycastHit.
Here is what you can get from it (mind minor changes over the Unity version history): Unity - Scripting API: RaycastHit

Once you have a grip on the game object or any of its components, you can call GetComponent() on that, since this is a method that is available in the GameObject type and all Component types. The transform is a type of component - one to which we get access via the RaycastHit, and one of which we know that it is there in any GameObject.

3 Likes

@daberny has nailed it on the head with this answer.

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms