How do I call a function in another gameObject's script?

I have a gameObject A with script A, how do I then call a function in gameobject b's script b?

Like this:

using UnityEngine;
public class ScriptA : MonoBehaviour
{
  public ScriptB other;

  void Update()
  {
    other.DoSomething();
  }
}

and in a seperate script:

using UnityEngine;
public class ScriptB : MonoBehaviour
{
  public void DoSomething()
  {
     Debug.Log("Hi there");
  }
}

Notice how ScriptA has a public field, with a type of ScriptB. This is a nice trick, where you can now drag a gameobject that has a ScriptB attached onto this "other" field in the editor. Unity automatically realizes that you didn't ask for a gameobject, but you asked for a ScriptB, so it will fill that field with the ScriptB instance, instead of with the gameObject.

Alternatively, if you don't like the "direct reference" made in the Editor by dragging the gameobject with scriptb onto the "other" variable, you can get a reference trough GameObject.Find("somename") instead:

GameObject go = GameObject.Find("somegameobjectname");
ScriptB other = (ScriptB) go.GetComponent(typeof(ScriptB));
other.DoSomething();

GameObject.Find() is a pretty slow operation though, so whenever you can do the direct reference, that's recommended.

For more detailed information see this section of the help: http://unity3d.com/support/documentation/ScriptReference/index.Accessing_Other_Game_Objects.html

This can either be done by a static reference (if you know the other object already upfront) or a dynamic lookup (finding a gameObject at runtime).

With a static reference, you create a link from ScriptA to gameObject b's ScriptB and call then any function in ScriptB. Example:

ScriptA attached to gameObject a:

var linkToScriptB : ScriptB;

function Update()  {
   ...
}

Now in the inspector, drag gameObject b with ScriptB attached to it to the free linkToScriptB slot in the gameObject A's script. Et voila, you can call now inside ScriptA a function like "Test()" in ScriptB like this:

linkToScriptB.Test();

The dynamic lookup is used when you don't know gameObject b upfront, but sometime later in your game. Then, instead of linking it in the inspector, you call at the appropriate place in your script something like this (in ScriptA):

linkToScriptB = GameObject.Find("gameObjectA").GetComponent(ScriptB);
linkToScriptB.Test();

The function "GameObject.Find(..)" will locate the other gameObject by its name. The return value would be a gameObject. Now that we want the ScriptB from that gameObject, we retrieve a reference to the ScriptB by calling the GetComponent function.

Also note there is a section called Accessing Other Game Objects in the Unity Script reference documentation that expands upon this in detail.

public class ScriptA : MonoBehaviour
{
public GameObject other;

   void Update()
   {
     other.GetComponent<ScriptB>().DoSomething();
   }
 }

Hi! I also had this problem and I got answers from this link.

Here