Call a function in a different script, using javascript.

How can i in script A call a custom function in script B, using javascript?

Try this.


Script A

var ScriptB : ScriptB; //This should be were Script B goes

function Update () {
    ScriptB.Test();
}


Script B:

var test : int = 0;

function Test () {
    test++;
}


In this example Script A tells Script B to add 1 to the 'test' integer ever frame.

Use the function GetComponent() to find a script attached to a GameObject.

Reference and Examples

  1. You can use Component.GetComponent. But it will work only if the target script is attached to your object or you need to have reference to another object to invoke GetComponent on it.

  2. You can create static methods in your script and invoke it from anywhere .

Helle i know this post is old, but the best practice is to use “BroadcastMessage” to call a methode name on all gameobjects