I am going to need to call a function in a script in another object. How may I do this?
if (Input.GetKeyDown(“escape”)){
on this line you have an opening brace that you never close.
You can make this by using the script component of the object and a little of C# reflection. Consider that you have a game object named ‘GameObjectA’ that has a script named ‘ScriptA’ with a method ‘YourMethod’ like:
public string YourMethod()
{
return "A returned string";
}
So, to retrieve and use it you need to:
// get game object named 'GameObjectA' from scene
GameObject goA = GameObject.Find("GameObjectA");
// get its script component of type 'ScriptA'
ScriptA scriptA = goA.GetComponent<ScriptA>();
// get the method 'YourMethod' from its script component
MethodInfo m = scriptA.GetType().GetMethod("YourMethod");
// invoke the retrieved method using 'scriptA' instance
object o = m.Invoke(scriptA, new object[] {});
// cast the returned object and use its value in your code (in this case a returned string)
string ret = (string) o;
// ...
Remember the using System.Reflection;
If you want to call a function from another script, then in the other script put:
var script : ScriptName //Here you put the name of the script you want to call
function Start(){
script.function() //Here you put the name of the function you want to call
}
In the inspector drag the gameobject containing the first script into the second script’s (the one above) place.