In this video we see how to GET A COMPONENT OF A SPECIFIC TYPE that is assigned to a GameObject, for example an AudioSource component, Collider component, MeshRenderer or a Script that we have created and assigned to a GameObject.
This allows us to find the reference of that component and thus be able to read its variables and execute its public functions, for example to access the GameObject to which that component is assigned.
With this method we can extract a component from a GameObject at run time (i.e. while the game or application is running) and it requires that WE HAVE THE REFERENCE of the GameObject to which we want to extract the component and THAT THE GAMEOBJECT HAS A COMPONENT OF THE INDICATED TYPE ASSIGNED, because if the component is not present, the function will return null and this could cause a NullReferenceException error.
The instruction to get a component of a specific type in Unity is "GetComponent". To indicate the type of component to look for in the GameObject the signs "less than" and "greater than" are used, which I can't write in this description, see the video to know how to indicate the type of component to look for.
It is not recommended to use this method in an update function such as Update or FixedUpdate because getting a component from a GameObject in Unity requires, in the worst case, to analyze all the components of the GameObject. It is more practical to get the component once and save the reference in a variable to use it when we need it.
The GetComponent function can be used directly which automatically searches for the indicated component in the same GameObject to which the Script is assigned (the script where GetComponent is executed). Or we can apply it on the reference of a specific GameObject, which will make Unity search among the components of that particular GameObject, for example by doing:
aGameObject.GetComponent...
INTRODUCTION VIDEO OF THE REFERENCE SERIES IN UNITY:
• Video
____________________________________________________________
LINKS
Portfolio: https://gamedevtraum.com/en/portfolio...
LinkedIn: / gamedevtraum
Downloads: https://gamedevtraum.itch.io/
Contact: / gamedevtraum
____________________________________________________________