Unity Coding — Scripts Talking
In our study of collisions we saw that there sometimes needs to be communication between objects. This is something that is obvious when thinking about playing video games and seeing the interactions between so many objects. It is often not only the objects themselves, but the scripts that need to really talk.
We already know that when a variable is public, it is accessible from others scripts. But what about functions or the script itself? We have tricks to figure this out. As far as functions, it is the same answer as the variables. Add a ‘public’ in front of the function and there you have it. It is a public function.
This does not solve everything though. We still need to learn the proper way to talk to the script containing any and all public variables and/or functions. This is done with a method called GetComponent. Just like the Rigidbody and Renderers, scripts added to an object are components of that object. So this method will let us ‘get’ them. Let’s say you have a reference to the object containing the script. A good example of this is in an OnCollisionEnter() or OnTriggerEnter();
The ‘other’ in both cases is a reference to another object, most likely containing a script. If you know the name of that script, you can use:
Now you have a reference to that script. Any public variable or function is now available to you.
We did make a pretty large assumption though. We assumed this script existed on the object we know. This could cause a bad error when trying to access the public elements inside. We can avoid this, however, with a little condition.
After using GetComponent to access a script, simply check whether or not that it actually exists. If it does, continue what you wanted to do in the first place. There you have it, communication between scripts is a beautiful thing.