- Home /
Send Message?
I want to activate a function of of one script with another. I've been told to search up at GetComponent and SendMessage but it's not making any sense to me (didn't help very much -_-). I'm still sort of a beginner, so can someone give me a simple explanation of how it works?
Try these links, to see if they help.
http://docs.unity3d.com/412/Documentation/ScriptReference/index.Accessing_Other_Game_Objects.html
http://answers.unity3d.com/questions/313568/why-do-i-have-to-use-getcomponent-function.html
http://www.unity3dstudent.com/2011/02/beginner-b28-sendmessage-to-call-external-functions/
http://unity3d.com/learn/tutorials/modules/beginner/scripting/getcomponent
http://answers.unity3d.com/questions/7555/how-do-i-call-a-function-in-another-gameobjects-sc.html
I was asking for a nice, short, and concise explanation, but I'll check these out anyway...
UPDATE: Not working out for me. It's not making sense.
You sure you did the Unity Tutorial on GetComponent linked above? That should be about as simple an explanation as possible to get you started, other than someone co$$anonymous$$g to your house and $$anonymous$$ching you to how to write the code. If you weren't able to understand some of the concepts in that tutorial, you probably need to start from the beginning of the Unity Scripting Tutorials or/and the Unity Editor Tutorials
Answer by Simba · Jul 07, 2014 at 07:06 PM
SendMessage invokes a function on every script on the game object you call it on. For example, if you say:
gameObject.SendMessage("Foo");
And, in another (or the same) script, on the same gameobject, you have:
function Foo () {
print("Hello");
}
Then your call to SendMessage will run the function Foo.
The downside of this is that if you have multiple instances of the same script, it will run the same for all of them, because that's what SendMessage does. It's great for, say, when you have six guns, all with their own script on the same object, and you want to call Fire() at the same time on all of them. But it's not great if you want to fire just one gun. That's this method comes in:
// Your script where you want to call the function
var otherScript : NewScript;
function Start () {
otherScript = gameObject.GetComponent(NewScript); // Use GetComponent to find the script.
//If you delete the above line you can drag a NewScript to this script's otherScript variable in the Inspector window, which is useful
otherScript.Foo(); // This runs Foo() on the otherScript
}
// NewScript.js
function Foo () {
print("Hello");
}
(Note: Untested code, NewScript might be a reserved name, but you get the idea) Hope this helps.