Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • 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
3
Question by NhommeBeurreOne · Jan 07, 2012 at 11:26 PM · javascriptvariablehudaccessing

Accessing A Variable From Another Script

Hello Guys,

I know that this question has been asking a lot of time, but i didn't found the perfect answer. The answers that I found was about GameObject and I'm talking about a variables. How can I access to a variable that is in a script with another script ? I found that documentation but I didn't found anything about variable(I'm not English so I may have passed it without seen that was talking about variables) so please if that wright can you specified witch part it is.

Here the script :

 var Clips : int = 20;

 

And I would like to access the variable "Clips" with another script to make it a HUD to show to the player the number of Clips that left and do the same thing for the bullets.

Thank You for you're help,

NbO

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

4 Replies

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

Answer by aldonaletto · Jan 08, 2012 at 12:08 AM

Accessing a script variable from another script is somewhat tricky in the OOP world, for sure: any object may have several clones in scene, each one with its own script instance, and each script with its own local clones of each variable. Due to this reason, you always need a reference (transform, gameObject, collider etc.) to the object whose script you want to access; how you get this reference depends on each case. If both scripts are attached to the same object, you can just use GetComponent(ScriptName) without any reference (the object owner of both scripts is assumed by default); if the target script is in a child, you can use GetComponentInChildren(ScriptName), again without any explicit reference; if the target script is in a different object, however, you must use reference.GetComponent(ScriptName), and this reference may be assigned to a variable in the Inspector (or be get from the info passed in OnCollision or OnTrigger events, for instance):

 var targetObj: Transform; // drag the object with the Clips variable here
 
   // get a reference to the target script (ScriptName is the name of your script):
   var targetScript: ScriptName = targetObj.GetComponent(ScriptName);
   // use the targetScript reference to access the variable Clips:
   targetScript.Clips += 10;
   print("Clips="+targetScript.Clips);
 
   // In C# the syntax would be different:
   ...
   ScriptName targetScript = targetObj.GetComponent<ScriptName>();
   ...

The generic GetComponent version returns the ScriptName type, thus you can access its variables or functions directly. The other GetComponent version returns a reference of type Component, which must be assigned to a ScriptName variable to allow access to the ScriptName variables and functions. In JS, GetComponent(ComponentType) returns the correct type (see @Eric5h5's comment below).

EDITED: @Eric5h5 and @Bunny83 linked to Accessing Other Game Objects in the docs, and it's the best reference, for sure (read it!). In the second example of its first item, a better way to access the target script is shown:

 var targetScript: ScriptName; // drag the object with the script ScriptName here
 
   // access the variable Clips directly with targetScript:
   targetScript.Clips += 10;
   print("Clips="+targetScript.Clips);

  


NOTE: See below the essence of the original Accessing Other Game Objects page, which disappeared from the docs:

Overview: Accessing Other Game Objects

Most advanced game code does not only manipulate a single object. The Unity scripting interface has various ways to find and access other game objects and components there-in. In the following we assume there is a script named OtherScript.js attached to game objects in the scene.

 function Update () { 
      var otherScript: OtherScript = GetComponent(OtherScript); 
      otherScript.DoSomething(); 
 }

1) Through inspector assignable references.

You can assign variables to any object type through the inspector:

 // Translate the object dragged on the target slot
 
 var target : Transform;
 function Update () {
     target.Translate(0, 1, 0);
 }

You can also expose references to other objects to the inspector. Below you can drag a game object that contains the OtherScript on the target slot in the inspector.

 // Set foo DoSomething on the target variable assigned in the inspector.
 
 var target : OtherScript;
 
 function Update () {
     // Set foo variable of the target object
     target.foo = 2;
     // Call do something on the target
     target.DoSomething("Hello");
 }

2) Located through the object hierarchy.

You can find child and parent objects to an existing object through the Transform component of a game object:

 // Find the child "Hand" of the game object 
 // we attached the script to
 
 transform.Find("Hand").Translate(0, 1, 0);

Once you have found the transform in the hierarchy, you can use GetComponent to get to other scripts.

 // Find the child named "Hand".
 // On the OtherScript attached to it, set foo to 2.
 transform.Find("Hand").GetComponent(OtherScript).foo = 2;
 
 // Find the child named "Hand".
 // Call DoSomething on the OtherScript attached to it.
 transform.Find("Hand").GetComponent(OtherScript).DoSomething("Hello");
 
 // Find the child named "Hand".
 // Then apply a force to the rigidbody attached to the hand.
 transform.Find("Hand").rigidbody.AddForce(0, 10, 0);

You can loop over all children:

 // Moves all transform children 10 units upwards!
 
 for (var child : Transform in transform) {
     child.Translate(0, 10, 0);
 }

See the documentation for the Transform class for further information.

3) Located by name or Tag.

You can search for game objects with certain tags using GameObject.FindWithTag and GameObject.FindGameObjectsWithTag. Use GameObject.Find to find a game object by name.

 function Start () {
     // By name
     var go = GameObject.Find("SomeGuy");
     go.transform.Translate(0, 1, 0);
 
     // By tag
     var player = GameObject.FindWithTag("Player");
     player.transform.Translate(0, 1, 0);
     
 }

You can use GetComponent on the result to get to any script or component on the found game object

 function Start () {
     // By name
     var go = GameObject.Find("SomeGuy");
     go.GetComponent(OtherScript).DoSomething();
 
     // By tag
     var player = GameObject.FindWithTag("Player");
     player.GetComponent(OtherScript).DoSomething();
 }

Some special objects like the main camera have short cuts using Camera.main.

4) Passed as parameters.

Some event messages contain detailed information on the event. For instance, trigger events pass the Collider component of the colliding object to the handler function.

OnTriggerStay gives us a reference to a collider. From the collider we can get to its attached rigidbody.

 function OnTriggerStay( other : Collider ) {
     // If the other collider also has a rigidbody
     // apply a force to it!
     if (other.rigidbody)
         other.rigidbody.AddForce(0, 2, 0);
 }

Or we can get to any component attached to the same game object as the collider.

 function OnTriggerStay( other : Collider ) {
     // If the other collider has a OtherScript attached
     // call DoSomething on it.
     // Most of the time colliders won't have this script attached,
     // so we need to check first to avoid null reference exceptions.
     if (other.GetComponent(OtherScript))
         other.GetComponent(OtherScript).DoSomething();
 }

Note that by suffixing the other variable in the above example, you can access any component inside the colliding object.

5) All scripts of one Type

Find any object of one class or script name using Object.FindObjectsOfType or find the first object of one type using Object.FindObjectOfType.

 function Start () {
     // Find the OtherScript which is attached to any game object in the scene.
     var other : OtherScript = FindObjectOfType(OtherScript);
     other.DoSomething();
 }







Comment
Add comment · Show 12 · 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 Eric5h5 · Jan 08, 2012 at 12:17 AM 0
Share

That's not correct about GetComponent, at least with Unityscript...the non-generic version also returns the type, rather than Component, and is a little faster. As long as you don't use strings anyway. So in Unityscript there's no reason to use the generic version of GetComponent.

Also, even if GetComponent returned Component (which it does if you use strings), assigning it to a ScriptName variable isn't enough, unless you're relying on dynamic typing. You have to cast it to the correct type, but that also means you don't need to assign it to a variable. i.e.,

 print("Clips="+(targetObj.GetComponent("ScriptName") as ScriptName).Clips;

But that's the worst case (namely, using quotes); what you actually want is:

 print("Clips="+targetObj.GetComponent(ScriptName).Clips;
avatar image NhommeBeurreOne · Jan 08, 2012 at 12:18 AM 0
Share

Thank You aldonaletto for your answer it looks awesome but I'm not sure if you're script is not in C# because I'm talking about JavaScript, so can please just tell me.

avatar image aldonaletto · Jan 08, 2012 at 12:31 AM 0
Share

Don't worry, it's pure javascript (C# doesn't use the var keyword in the variable declaration). The generic GetComponent. exists in javascript too, but it seems you will not need it (read @Eric5h5 comment)

avatar image Eric5h5 · Jan 08, 2012 at 12:31 AM 0
Share

It's not C#.

avatar image aldonaletto · Jan 08, 2012 at 12:48 AM 0
Share

@Eric5h5, I used to think that GetComponent(Type) returned Type, but became unsure when read in the docs that it returns Component! Is this an error, or GetComponent(Type) may return Component in some cases?

Show more comments
avatar image
1

Answer by Bunny83 · Jan 07, 2012 at 11:35 PM

The first thing you should learn is how to ask a question in a way it can be answered. First of all you should include relevant parts of your script and don't post a 5-page-script which doesn't contain any useful infomation except this line:

 var Clips : int = 20;

Second, you said you "tried to access the variable", but you don't say what you've done. You said you've found other questions that are phrased even more explicit, so what is in your question that makes it worth to ask the question again in the most general way it's even possible?

Usually, in most cases, the documetation has an example even for the most general things.

Comment
Add comment · Show 1 · 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 NhommeBeurreOne · Jan 08, 2012 at 12:15 AM 1
Share

I edit my post and ask if it's still unclear

avatar image
1

Answer by Eric5h5 · Jan 07, 2012 at 11:37 PM

The perfect answer has been stated many, many times. You should easily have found it with a search. http://unity3d.com/support/documentation/ScriptReference/index.Accessing_Other_Game_Objects.html

Comment
Add comment · Show 2 · 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 BMRX · Feb 16, 2016 at 12:15 PM 0
Share

Link no longer valid.

avatar image meat5000 ♦ · Feb 16, 2016 at 01:01 PM 0
Share

The Accessing_other_game_objects.html seems to no longer exist within the Docs but the page still exists within the 410 archive.

http://docs.unity3d.com/410/Documentation/ScriptReference/index.Accessing_Other_Game_Objects.html

When a link has expired, sticking the html page name in to google usually turns out a positive result.

avatar image
0

Answer by richardboegli · Apr 10, 2017 at 12:42 PM

@aldonaletto You've done a great job of explaining. As this page is a top result on search engines, pointing to revised location of documentation could help future users who want to know more: https://docs.unity3d.com/Manual/ControllingGameObjectsComponents.html

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

13 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

Related Questions

Accessing another var on another script 1 Answer

Changing The Value Of A Variable From Another Script (JavaScript) 1 Answer

Unknown identifier, OnCollisionEnter Error 1 Answer

How could you access a script of varying name? 5 Answers

accessing a variable from another script. 3 Answers


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