- Home /
Call a function in a different script, using javascript.
How can i in script A call a custom function in script B, using javascript?
Answer by AquaGeneral · Feb 08, 2010 at 12:10 PM
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.
So the syntax is: "nameOfOtherScript.nameOfFunction();" ?
Spot on. With this approach it is in theory (at least) quicker than the GetComponent method, as it doesn't have too look for anything on the initial run.
what do we put after we name the variable scriptB?
var ScriptB : What goes here?;
I am trying this for two cubes and my scripts are: cube1.js var cube2:cube2; function Start () {
}
function Update () {
cube2.rot();
}
cube2.js function rot() { if (Input.Get$$anonymous$$ey($$anonymous$$eyCode.A)) transform.Rotate(Vector3.up); } but its not working please tell me why it is not working?
Answer by efge · Feb 08, 2010 at 12:48 PM
Use the function GetComponent() to find a script attached to a GameObject.
Answer by SergeyLavren · Jan 01, 2012 at 04:33 PM
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.
You can create static methods in your script and invoke it from anywhere .
Answer by Pondomaniac · Mar 27, 2015 at 02:14 PM
Helle i know this post is old, but the best practice is to use "BroadcastMessage" to call a methode name on all gameobjects
https://docs.unity3d.com/ScriptReference/Component.BroadcastMessage.html
Why are you proposing a new answer to a 5yr old question that's already been answered with the "best practice" answer? (to create a public reference to the other script)
Your answer
Follow this Question
Related Questions
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
object facing wrong way, Java script Quaternion 1 Answer
Insantiate once only 2 Answers
Finding the length of a string 2 Answers
Picking a language... 1 Answer