x


How to make a global variable in Unity?

im trying to make a global variable so other scripts can do stuff with it. How do i make a variable global?

edit using java

more ▼

asked Mar 05, 2011 at 05:17 PM

NathanDaniels gravatar image

NathanDaniels
60 4 4 12

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

3 answers: sort voted first

I'm pretty sure this has already been answered but you can always put

static var

infront of something and that makes it accesible from other scripts.

more ▼

answered Mar 05, 2011 at 05:20 PM

AngryOldMan gravatar image

AngryOldMan
2.7k 36 33 63

So simple but thank you!

Sep 26, 2012 at 08:28 AM Nercoe

does this still work it doesn't seem to do you have to put it in both scripts i tried that too and it didnt work

Jul 09 at 03:37 AM UNDERHILL

you don't need to put the definition both places. in c#, you would write static in front of the variable, then in the other script you can access by typing

origscriptname.variablename

Jul 09 at 03:49 AM vickygroups
(comments are locked)
10|3000 characters needed characters left

You can use the "static" modifier. In C#, that would be

public static int myInt = 0;
more ▼

answered Mar 05, 2011 at 05:20 PM

jashan gravatar image

jashan
11.5k 45 60 138

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

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";
}
more ▼

answered Sep 04, 2013 at 12:15 AM

Cawas gravatar image

Cawas
2.3k 114 102 123

(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:

x1358
x165

asked: Mar 05, 2011 at 05:17 PM

Seen: 22037 times

Last Updated: Jul 09 at 03:49 AM