Script communication is arguably one of the most important and most struggled with aspects of programming for new developers. But by learning and understanding how this works, you will be opening yourself up to a world of possibilities in the world of code.
How does it work?
Well to start, you cannot communicate with another script unless you can access the object to which it’s attached. If your scripts are on the same object, then the process is as simple as a few lines of code. But if they are on different objects, you’ll have to create a reference to the other object.
There are a few different ways to go about this, and which one is best can vary depending on the scenario. But first and foremost, you are going to have to “Cache” either the script itself or the object it’s attached to.
Ok, but how do I use it?
Well, it depends.
If you are using one script to try and access another script that's attached to the same object.
Just “Cache” the second script and give it a name. Then define the name in the Start() or Awake() method by calling the second script’s component.
Otherwise, if you’re trying to access scripts that are attached to different objects in the scene.
You’ll need to create a reference to the other objects somehow. This can be done in a few different ways!
You can create a direct link to the other gameobject in the hierarchy.
Create a “public GameObject” and cache the object that holds the other script in the inspector. Then just create a second variable to cache that object’s script component.
Or you can search the hierarchy for an object by its name.
Keep in mind that spawned prefabs will enter the hierarchy with “(Clone)” at the end of their name which must be accounted for if you plan to find it by its name!