I want to run a function in another script in another object.
Basically I want to run a test function in my Enemyscript.js file which is located in the Enemy object from my Bullet_Movement.js located in a totally separate object, Bullet. I just want to know how to run the simple function, then Ill modify it myself.
Enemyscript.js: #pragma strict
public var Health : float = 100f;
function Start () {
}
function Update () {
}
function RemoveHealth () {
Debug.Log(1 + 1);
}
Bullet_Movement.js: #pragma strict
public var speed : float = 10f;
public var Enemy : GameObject;
private var myOtherClass : AnotherClass;
function Start () {
myOtherClass = new Enemyscript();
myOtherClass.RemoveHealth();
}
var thePositionToMoveTo : GameObject;
function OnCollisionEnter2D(other : Collision2D) {
Debug.Log("Hit");
if(other.gameObject.tag == "Respawn") { //Or whatever
gameObject.transform.position = thePositionToMoveTo.transform.position;
}
}
function Update () {
transform.Translate(Vector2.up * speed * Time.deltaTime);
}
Answer by ZefanS · Nov 19, 2015 at 08:04 AM
In general if you have two GameObjects, each with a script attached, you can call one script from the other by getting a reference in one script to the other script:
Script1.js attached to GameObject1 - we want to call HelloWorld():
#pragma strict
function HelloWorld()
{
Debug.Log("Hello World");
}
Here are a few ways to reference and call HelloWorld() from Script2.js attached to GameObject2:
Declare GameObject1 as a public variable and assign it in the Inspector, then use GetComponent:
#pragma strict
public var gameObject1 : GameObject //Assign GameObject1 in the Inspector
function CallHelloWorld()
{
gameObject1.GetComponent.<Script1>().HelloWorld();
}
Declare GameObject1 as a public variable and get a reference at runtime, and again use GetComponent:
#pragma strict
public var gameObject1 : GameObject;
function Start()
{
gameObject1 = GameObject.Find("GameObject1");
}
function CallHelloWorld()
{
gameObject1.GetComponent.<Script1>().HelloWorld();
}
Get the entire reference at runtime when you wish to call the function:
#pragma strict
function CallHelloWorld()
{
GameObject.Find("GameObject1").GetComponent.<Script1>().HelloWorld();
}
Declare Script1 as a variable and get a reference to it directly in one of the same ways, eg:
#pragma strict
public var script1 : Script1 //Assign in the Inspector
function CallHelloWorld()
{
script1.HelloWorld();
}
The method you'll use will depend on the particular scenario. For instance, if you are trying to access a script attached to a GameObject that gets instantiated at runtime, then you won't be able to assign the variable in the Inspector and instead will need to get the reference to the script after the object has been instantiated. However, if the GameObject exists from the start of the Scene, it may be simpler to just assign it in the Inspector.
Hope this makes things a bit clearer.