Script communication is important and inevitable
How can you get access to a variable from another script?
Script communication is important in coding. It allows us to get access to another game object’s components (Variables and methods must be public if they are private. You can’t get access to those from another script.)
So let’s get to it! :) I will show here two ways you can do it using GetComponent
FindObjectOfType
- GameObject.FindObjectOfType<NPC>();
We have our Player Script and NPC Script where is the information we want.
First, we need something where we can store our information about another script
Then in Start() we write this code to get access to our NPC GameObject
Inside the NPC, I created an NPC script which has public int coins = 10;
And now in our Player script, we want to decrease the coin amount when we click our mouse(0). (Left mouse button)
FindGameObjectWithTag
- GameObject.FindGameObjectWithTag(“Bob”);
And now we do the same with tags! :)
All we need to change here is our start function and what we wrote inside the if statement.
Remember to add Tag in your game object which you are trying to get access to! In my case, I added a tag called Bob
We need to create a GameObject to hold the information
Our start should look like this
And our if statement in Update should look like this
Now we can do the same thing, decrease the coin amount by clicking! :)
Steal Bob’s money! :D
Thank you for reading this, Get Component has always been a bit off over my head subject. But it’s a really interesting subject and I recommend learning more about it.
Much love and see you in the next one! :)