Searching for Components via Scripts in Unity
Accessing components of an object is something you will do often via scripts and it may not be as intuitive at first…even if the component you want access to.
The one exception is the “Transform” which can be accessed directly.
For example, if you wanted to change the material of an object, you first need to access the material component with “GetComponent<Material>();
Let’s take a look at a basic cube object:
Here you can see all of the components that are added to the basic cube by default.
If we wanted to change the color of the cube, we would first access the material and then the color:
One thing to note is that GetComponent is an expensive method, so it’s best to cache it like this:
In this example, we first cache the MeshRenderer and name it _renderer. Then we get access to the component within the Start() Method. Finally we define the new color.
Again, this is the procedure for accessing components within any object that the script is attached to (excluding the Transform).
So what happens if we want access to a component of an object that isn’t attached…like another script?
The process is similar with the added step of finding the game object that the script is attached to first. If we wanted to access a method “Damage()” within an Enemy object, we would do so like this:
In the above example, we are declaring a type Enemy which is the script component. Within the Start() method, we set _enemy to the component <Enemy> which is attached to the object that happens to also be called “Enemy”.
If the component you want access to is attached to the same object that the script is attached to, you can simply call GetComponent<Component>():
If the component is attached to a separate object, you can use the “GameObject.Find(“Object”).GetComponent<Component>():