I have a script that contains mouse event that detects the action when the button is clicked. I want to access a method from another script when I click a button
var barrel:GameObject;
function OnGUI () {
// Make a background box
if (GUI.Button (Rect (20,40,80,20), "Level 1")) {
// I WANT HERE TO PUT THE CODE TO ACCESS THE METHOD FROM ANOTHER SCRIPT ATTACHED ON ANOTHER GAME OBJECT
}
if (GUI.Button (Rect (20,70,80,20), "Level 2")) {
}
}
Let’s suppose the target script is called MyScript.js, and the function is MyFunction(). If you have only one instance of this script, you can use this:
var script = FindObjectOfType(MyScript);
script.MyFunction();
But if you have several instances of this script, you must first find the one you want with Find(“name”), then get the script with GetComponent:
var obj = GameObject.Find("turret1");
var script = obj.GetComponent(MyScript);
script.MyFunction();
Take a look at:
http://unity3d.com/support/documentation/ScriptReference/GameObject.GetComponent.html
if (GUI.Button (Rect (20,40,80,20), “Level 1”)) {
var differentScript = gameObject.Find(“objects name”).GetComponent(scriptName);
differentScript.method();
}