- Home /
Best ways for two MonoBehaviour classes to communicate?
I come from a strong C++ background and work with other game engines, I just picked up Unity a couple days ago and run into the problem of separating out classes correctly.
Specifically, I have a separate class for GUI work, that when it detects a button press for example, I need my 'main' program to detect it to do other work. What is the best way to do this? Since C# doesn't really seem to use pointers, I'm not sure how to best pass info between classes.
This is, of course, no problem when the classes do not need to be set on a game object (do not need MonoBehaviour functionality), but when 2 or more MonoBehaviour derived classes need to talk, how does one do this efficiently?
Thank you.
Answer by robertbu · Mar 22, 2013 at 12:42 AM
Generally, through one of several methods, you get a reference to the instance of a specific class. See Accessing other Game Objects. There are other methods. See C# Events and Delegates. For dealing with communication within a particular game object or game object hierarchy, do a search in the reference for "SendMessage" and "BroadcastMessage" for the various forms of this type of communication.
I didn't have the $$anonymous$$arma until now to upvote. Delegates and Events do the trick.
Answer by Zygy · Mar 22, 2013 at 04:26 AM
if both of your objects are on gameobjects your best bet is to get a refrence to that gameobject and then a refrence to the script from that
Gameobject go = GameObject.Find("name");
Class c = go.GetComponent<Class>();
c.function(paramaters);
c.var = data;
hope this helps
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Can I use c plus plus to program a game in unity? 1 Answer
Is it possible to assign a script that derives from MonoBehaviour from an external library? 1 Answer
Is it possible to make sealed overridden MonoBehaviour method. 0 Answers
Bool is not turning false 1 Answer