• Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
32
Question by Martin Schultz · Oct 20, 2009 at 07:58 AM · gameobjectscriptingbasicsreferencelink

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?

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

5 Replies

· Add your reply
  • Sort: 
avatar image
105
Best Answer

Answer by Lucas Meijer 1 · Oct 20, 2009 at 08:39 AM

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

Comment
Add comment · Show 8 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Martin Schultz · Oct 20, 2009 at 09:25 AM 0
Share

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

avatar image Lucas Meijer 1 ♦♦ · Oct 20, 2009 at 09:41 AM 0
Share

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

avatar image SisterKy · Dec 11, 2009 at 03:25 AM 1
Share

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 $$anonymous$$artin's (and the Script-reference-link) are JS.

avatar image rocket5tim · Dec 13, 2009 at 04:05 PM 1
Share

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.

avatar image jashan · Dec 24, 2009 at 10:31 AM 1
Share

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).

Show more comments
avatar image
7
Best Answer

Answer by Keli Hlodversson · Oct 21, 2009 at 10:36 AM

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

Comment
Add comment · Show 5 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Daniel G · Jul 22, 2013 at 02:39 PM 0
Share

@$$anonymous$$eli_Hlodversson The link is correct BUT the that section of the docs is down error "PageNotFound"

avatar image VTW · Dec 22, 2013 at 11:00 PM 0
Share

Updated link to - Accessing Other Game Objects

avatar image BinhNM · Aug 11, 2015 at 04:10 PM 2
Share

I click the link and it say: Page not found. Please update the link.

avatar image drynyn · Dec 17, 2016 at 11:43 AM 1
Share

Current link: https://docs.unity3d.com/410/Documentation/ScriptReference/index.Accessing_Other_Game_Objects.html

avatar image kaolin · Sep 02, 2019 at 01:55 PM 0
Share

Link (2019.2) — https://docs.unity3d.com/$$anonymous$$anual/ControllingGameObjectsComponents.html

avatar image
11

Answer by Martin Schultz · Oct 20, 2009 at 09:24 AM

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.

Comment
Add comment · Show 4 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image MP0732 · Jun 22, 2012 at 03:25 PM 0
Share

$$anonymous$$artin Schultz wrote, "var linkToScriptB : ScriptB;"

Don't you mean: "var linkToScriptB : $$anonymous$$onoScript;" ?

Otherwise, Unity returns an error.

avatar image MP0732 · Jun 22, 2012 at 03:25 PM 0
Share

Very helpful tip, though. Thanks.

avatar image Bunny83 · Jun 22, 2012 at 05:11 PM 1
Share

@$$anonymous$$P0732: No. You mixed up $$anonymous$$onoScript with $$anonymous$$onoBehaviour. $$anonymous$$onoScript 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 $$anonymous$$onoBehaviour.

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

$$anonymous$$onoScript 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.

avatar image MP0732 · Jun 27, 2012 at 05:08 PM 0
Share

O$$anonymous$$, I see. Thanks.

avatar image
1

Answer by bobueland · Nov 08, 2020 at 09:35 AM

 public class ScriptA : MonoBehaviour
  {
    public GameObject other;
  
    void Update()
    {
      other.GetComponent<ScriptB>().DoSomething();
    }
  }

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
0

Answer by lunaeight08 · Nov 18, 2020 at 11:16 AM

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

Here

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

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

Answers Answers and Comments

18 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

How to run function in another script with prefabs? C# 2 Answers

Call Functions Across Scripts, Null Object Error 1 Answer

Referencing a Public GameObject from another script. 2 Answers

Accessing Variables within another gameobject's script 2 Answers

How do you reference a GameObject in a C# script that is a part of that GameObject? 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges