Day 15 —Communication between one script to another
Hey and welcome!
Now I’ve got a special little bonus topic here for you today and it’s about script to script communication. We covered the GetComponent() method before that’s used when an object collides with us but what if we’re needing to access a method in another script on a separate object that we never collide with?
Well that’s where GameObject.Find() comes into play. Currently our enemies will keep spawning even after our player is destroyed but what I want to happen here is that when our _playerLives reaches 0 it stops the enemies from spawning.
Now our _playerLives variable is in our Player Script and our enemy spawning Coroutine is in our Spawner script so we’ll need to make use of GameObject.Find() in our Player script so that it can find the Spawner to communicate with it when the lives is 0.
First we create the following variable that has a type of SpawnBehaviour:
private SpawnBehaviour _spawner;
Now you’ll notice that our SpawnBehaviour type here is the same name as our SpawnBehaviour script/component, this is important because when you’re using GameObject.Find() you need to make sure that you have a reference to the component you’re looking for. With that in mind the next bit of code should look like this:
_spawner = GameObject.Find("Spawner")GetComponent<SpawnBehaviour>();
So we’re using GameObject.Find(“Spawner”) in order to locate our Spawner object that contains the SpawnBehaviour script making sure that we match the spelling and casing exactly. With that done we can get our spawn behaviour script as we have done in the past and then store an instance of it in our _spawner variable ready to use it whenever we want to in our Player script.
In the SpawnBehaviour script I added in two things:
private bool isPlayerAlive = true;public void OnPlayerDeath()
_isPlayerAlive = false;
Then I changed the condition in my while loop:
while (isPlayerAlive == true)
// Run my spawn code
That means that when my OnPlayerDeath() method gets called the enemies will stop spawning. So now it’s a case of heading back to the Player script and then adding in the following line to where I handle when the _playerLives reaches 0:
It’s pretty fascinating how you can get things to connect together like this right? That’s all from me for this one.