Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 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
1
Question by Astraeus · Jul 21, 2011 at 01:36 AM · globalglobal variable

Global variables questions

The only way I know of to declare a global variable is using static, which would be okay but sometimes when I try to access those variables from another script Unity says I must create an instance of the variable to use it? Aside from that, is there any way to make a global variable that I can also input in the inspector?

Comment
Add comment · Show 2
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 yoyo · Feb 03, 2012 at 06:01 AM 1
Share

If you want global variables without using static variables, consider having a singleton component, as described here -- http://answers.unity3d.com/questions/17916/singletons-with-coroutines.html

avatar image cregox · Sep 04, 2013 at 12:19 AM 0
Share

also, duplicate: http://answers.unity3d.com/questions/50716/how-to-make-a-global-variable-in-unity.html

5 Replies

· Add your reply
  • Sort: 
avatar image
4

Answer by Peter G · Jul 21, 2011 at 02:06 AM

FALSE a static var is NOT a global var. public makes a variable global, not static.

 //This is perfectly legal
 private static int myPrivateVar;

static makes a variable a class variable (its a little different than it is in C++) which means that it is associated with a class, not any of its instances. Public makes a variable or function accessible from outside functions. Hence the use of properties to encapsulate fields.

Unity will let you inspect any serializable public instance variable. Now that can sound intimidating if you aren't a programmer so let me break that down:

  • Serializable. All the Unity types, Mono objects, and the basic data types (int, float, string), and any classes you create that have the [Serializable] attribute.

  • public. The easiest one, they can't be private or protected.

  • Instance variable. As long as it isn't static, then its an instance variable.

The proper way to access a global variable (besides being through a property) is to get an instance of the class then read its value.

 //C#
 var instance = (MyClass)FindObjectOfType(typeof(MyClass));
 Debug.Log(instance.variableName);
Comment
Add comment · Show 3 · 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 Suyuanhan · Jul 21, 2011 at 09:51 AM 0
Share

quote:Serializable. All the Unity types, $$anonymous$$ono objects, and the basic data types (int, float, string), and any classes you create that have the [Serializable] attribute.

I don't really understand what you mean,can you give me some c# script so that I may get it easily.Thanks

avatar image Peter G · Jul 23, 2011 at 09:44 PM 0
Share

I actually made an oversight writing that so let me make a small correction. Not all $$anonymous$$ono objects are displayed in the inspector. Some are, but others such as $$anonymous$$ethodInfo (just to pick a random one) are not.

I'll give an example of each:

  //Unity Types;
  Transform t;
  Renderer r;
  //All classes in the Unity Scripting reference. *Note you could probably find one that isn't but generally, all classes that you would want to put in the inspector are available*

   //$$anonymous$$onoObjects 
   //such as System.Collections.Generic.List<T>();

   //Basic data types:
   int i;
   float myFloat = 2.0f;
   string myString = "";
   char myChar = 'a';
  
   //classes with [Serializable].
   [Serializable]
   class $$anonymous$$yClass {
         int a;
         int b;
    }
    //Unity will let you inspect this class. Try creating a variable of this type and Unity will make a little dropdown let with an array that shows all the public variables that also meet these requirements.
avatar image ZegTronic · Dec 08, 2014 at 11:01 PM 0
Share

PETER G, thank you sooo much, I've been searching for a way to keep my sword from taking damage for the player and this is my solution, this code works so well!

avatar image
1

Answer by UdevMike · Jul 21, 2011 at 01:51 AM

C# example: public static int myVar;

Access it by writing the name of the script followed by the variable name myScript.myVar = 5;

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 yoyo · Feb 03, 2012 at 05:58 AM 0
Share

Also note that you can declare a class like "public static class $$anonymous$$yGlobalVariables { ... }" -- you cannot create an instance of a static class, so this is a good idea if you have a class whose only purpose is to hold static global variables.

avatar image
1

Answer by Eric5h5 · Jul 21, 2011 at 02:04 AM

Don't use static unless you only want one instance of the variable. Making a variable public makes it global, static has nothing to do with it (private variables can be static). http://unity3d.com/support/documentation/ScriptReference/index.Accessing_Other_Game_Objects.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
avatar image
1

Answer by cregox · Sep 04, 2013 at 12:19 AM

Use `Singleton`s!

They're **much** better than using static.

Grab the singleton script above and simply use it as such:

 public class MyClass : MonoBehaviour {
     void Awake () {
         Debug.Log(Manager.Instance.myGlobalVar);
     }
 }

Manager.cs

 public class Manager : Singleton<Manager> {
     public string myGlobalVar = "whatever";
 }

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 joergzdarsky · Jul 12, 2015 at 11:43 AM 0
Share

Works perfect, thanks a lot! Very helpful!

PS: That post made me additionally think of reworking my "Camera$$anonymous$$anager" class as singleton, so that there is only one globally available class that has the references to all Camera objects in the scene.

avatar image
0

Answer by karl_ · Jul 21, 2011 at 02:05 AM

You can access local variables by creating an instance of the script. As an example, lets say you have someVariable located in scriptA, which is attached to gameObjectA. You want to access it from scriptB, which is attached to gameObjectB.

Within scriptB:

 function Update()
 {
      // Find the gameobject that scriptA is attached to
      var instanceGO     : GameObject.Find("gameObjectB");
 
      // Create an instance of the script
      var instanceScript : scriptA = instanceGO.GetComponent("scriptA");
 
      // Set someVariable to 0.
      instanceScript.scriptA.someVariable = 0;
 }
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 Eric5h5 · Jul 21, 2011 at 02:15 AM 2
Share

Don't use quotes with GetComponent; it's slower, and if you make a typo, you only find out at runtime ins$$anonymous$$d of when you compile the script.

avatar image karl_ · Jul 21, 2011 at 02:21 AM 0
Share

I did not know that, good bit of info to have. Also, as a side note- I normally wouldn't put a GetComponent() call in an Update function. This was just a cursory example bit.

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

9 People are following this question.

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

Related Questions

Create a persistent GameObject using Singleton 3 Answers

Access variable in another object 1 Answer

Global Scripts/Variables 1 Answer

How to make a global settings Editor Window for my game 0 Answers

Getting the (instantaneous) normal of a meshfilter object 2 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