Script Communication in Unity
Having your gameobjects able to communicate with each other, is an important part when making a game.
You’d make use of it for keeping score, knowing when the player is hit, etc.
Since Unity makes use of Components, that’s also what we will use to do our communication between them 😁
When we attach a script to a gameobject it gets added as a component.
My Player object has a transform, Sprite Renderer, Polygon Collider 2d, Audio Source and, a Player (script) component attached to it.
Above is two different examples of setting up references to Components.
One is getting a component on the same gameobject as the script itself is on, the other is for getting a component from a different object.
The audio source is on the same one, that’s why I don’t have to find it.GameObject.Find()
lets you look for a named object in the Hierarchy, one caveat is that it has to be active in the scene. That will return the GameObject, to get the actual component I want, I have to use the GetComponent method.
Once you have the references set up successfully, you are then able to communicate with that component, for instance by using a public method._spawnManager.GameOver();
to call the public method “GameOver” inside of my SpawnManager script.
If my player crashes into an enemy I’m using the colliders to get the components I need.
The enemy gets the Player component from the “other” reference passed in when OnTriggerEnter2D is called, and from there I can use the GetComponent method to get the Player script component, and then have the player take damage.
And there you have it, you gameobjects can now talk to each other 😀