x


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?

more ▼

asked Oct 20 '09 at 07:58 AM

Martin Schultz gravatar image

Martin Schultz
1.5k 9 20 31

(comments are locked)
10|3000 characters needed characters left

5 answers: sort voted first

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

more ▼

answered Oct 20 '09 at 08:39 AM

Lucas Meijer 1 gravatar image

Lucas Meijer 1 ♦♦
8k 19 43 85

Ah, hehe, you submited too while I was preparing the answer... :-)

Oct 20 '09 at 09:25 AM Martin Schultz

added your gameobject.find alternative to my answer to make it more complete

Oct 20 '09 at 09:41 AM Lucas Meijer 1 ♦♦

As I realized I'm not the only one who got confused by the "using UnityEngine;" and "public class"-declaration ... I'd like to point out that Lucas' answer is C#, while Martin's (and the Script-reference-link) are JS.

Dec 11 '09 at 03:25 AM SisterKy

Great thread. But how do you call functions between GO's when one of them is instantiated and one is not. For example, between the player (who is not instantiated) and an enemy who is. You cannot direct reference in this case and Find() is too slow.

Dec 13 '09 at 04:05 PM rocket5tim

Actually, the problem with "Find" is only a real problem when you do it frequently. What you'd usually do in that case (an object being instantiated at a later point in time): Do Find() once (e.g. only if you don't have the reference, yet) and then store it in a member variable (as in the above example).

Dec 24 '09 at 10:31 AM jashan
(comments are locked)
10|3000 characters needed characters left

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

more ▼

answered Oct 21 '09 at 10:36 AM

Keli Hlodversson gravatar image

Keli Hlodversson ♦♦
206 1 3 15

(comments are locked)
10|3000 characters needed characters left

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.

more ▼

answered Oct 20 '09 at 09:24 AM

Martin Schultz gravatar image

Martin Schultz
1.5k 9 20 31

Martin Schultz wrote, "var linkToScriptB : ScriptB;"

Don't you mean: "var linkToScriptB : MonoScript;" ?

Otherwise, Unity returns an error.

Jun 22 '12 at 03:25 PM MP0732

Very helpful tip, though. Thanks.

Jun 22 '12 at 03:25 PM MP0732

@MP0732: No. You mixed up MonoScript with MonoBehaviour. MonoScript is an editor class which is just a TextAsset and contains your script as text data. The actual class that is represented by your script is derived from MonoBehaviour.

The class-type equals your script name, so in Martin's example his script is called "ScriptB".

MonoScript won't let you assign instances of your script since your the class in your script is it's own type. The type name is the name of your script.

Jun 22 '12 at 05:11 PM Bunny83

OK, I see. Thanks.

Jun 27 '12 at 05:08 PM MP0732
(comments are locked)
10|3000 characters needed characters left
    GUITexture [] SubTexturas= Botones.GetComponentsInChildren<GUITexture>();

    print("COUNT: "+ SubTexturas.Length);
    for (int i = 0; i < SubTexturas.Length; i++) 
    {
       print("NAME: "+ SubTexturas[i].name);
    }

ó

     GameObject G= GameObject.Find ("Dificil"); //Nombre del GameObject
     if(G != null)
       G.guiTexture.enabled=true;
more ▼

answered Jan 03 at 09:56 PM

JxDarkAngel gravatar image

JxDarkAngel
1

(comments are locked)
10|3000 characters needed characters left

//Another option using JS scripts and global functions

//Script1 -

function OnMouseDown(){

myOtherScript.doSomething();

}

//Script2 - named "myOtherScript" with a method named "doSomething"

static var doSomething = function(){

Debug.Log("do something here");

};

more ▼

answered Nov 05 '12 at 03:15 PM

nick_taras gravatar image

nick_taras
1

(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x5081
x2087
x263
x148
x73

asked: Oct 20 '09 at 07:58 AM

Seen: 37071 times

Last Updated: Apr 19 at 01:57 AM