How to link scripts in Unity
Script communication in Unity takes some time getting used to.
By default you only can direct access the transform component from other scripts. Using the transform component you can access the root of the object.
1. GameObject Reference already in script — Collisions
For example in OnTriggerEnter you can get the “Player” script of the “other” object. Then access a “Damage()” function in the “Player” script.
Another example would be to access the MeshRenderer:
2. Creating a reference using the Inspector
Often we don’t have collisions that already give us a starting reference to another game object. By creating a variable accessible from the Inspector we can create a handle to access the object/component.
For example we want a reference to our Player game object from our enemy script.
Next drag the Player game object to the input box in the Inspector for our Enemy script.
3. Finding the using code — GameObject.Find
This third method allows us to search the “Hierarchy” for game objects.
Create a variable with the same type as the component you want to link/create a reference to.
private SpawnManager _spawnManager;
In the Start() function first search for the gameobject then search for the component. So first find the game object. There are three ways to find game objects: by name, tag or type.
GameObject.Find( ) — search for exact name in the hierarchy
GameObject.FindWithTag( ) — search for object with a certain tag
GameObject.FindObjectOfType() — search for object of certain (variable) type
It’s possible to search for multiple objects by tags or by type, which will return an array.
Then add the GetComponent<>() part. Make sure to have the same variable type as declared at the top of your script. In our example that would be ‘SpawnManager’.
_spawnManager = GameObject.Find("Spawn_Manager").GetComponent<SpawnManager>();
Suggest a change Thank you for helping us improve the quality of Unity Documentation. Although we cannot accept all…
Whenever a searched component is not found the game instantly game crashes. In Unity you’ll see an error:
Always create a verify if the component is not null also known as null checking. This way we can prevent the game from crashing.
Null checking example
Player player = other.transform.GetComponent<Player>();
if (player != null)