- Home /
Best pracices: Object communication without references
Hello,
I was wondering how I can get different scripts to communicate with each other and optimize the number of references used.
Answer by Phong · Nov 10, 2012 at 11:38 AM
You question is fairly abstract but you might be wanting something like the NotificationCenter script on the wiki http://wiki.unity3d.com/index.php?title=NotificationCenter.
Consider this situation, you have a SoundManager script that plays sounds when things happen in the game. You would like loose coupling between the sound manager and game objects. You don't want each character to have a reference to the sound manager and you don't want the SoundManager to know about the characters.
Solution:
SoundManager registers with the NotificationCenter to receive events they are interested in.
NotificationCenter.DefaultCenter().AddObserver(this, "OnBumperCollision");
NotificationCenter.DefaultCenter().AddObserver(this, "OnSkidding");
Character objects post notifications when something happens:
NotificationCenter.DefaultCenter().PostNotification(this, "OnBumperCollision");
These scripts don't need references to each other. The SoundManager script can be re-used in several different games without knowing anything about the Classes used by the characters.
Answer by sparkzbarca · Nov 10, 2012 at 07:47 AM
have one script call another. traditionally scripts are attached to a game object.
You call them by using getcomponent
in C# its
GameObject.GetComponent<script_name>();
you would store that instance of that script if you needed to reuse it so you didnt have to keep searching
script_name my_script;
my_script = GameObject.GetComponent<script_name>();