Sharing variables value between game objects?

An question to ask…

How can I setup a variable that is belonged to many game objects?

EX:
Once the variable value is changed in one object, all the other objects will be affected too.

Is it about global variables or defining classes? It confuses me.

Thanks for any help

If you want a variable to be defined on all objects, define it static:

JS:

static var someVariable : int;

C#

static int someVariable;

You can’t edit static variables from the inspector, mind you, and they don’t reset on scene-changes. It’s generally a bad idea to use them- it would be better to create a single object which contains all of the global data, an provide references to it in every object that needs it.

var someObject : GlobalVariables;

You need a script called ‘GlobalVariables’ and you need to assign it in the inspector once you’ve created the object.

If you speak of changing the variable in the editor.

You might be looking for prefab: http://unity3d.com/support/documentation/Manual/Prefabs.html

You can create a script with a public variable along with its default value, then assign it to a gameObject. Make a prefab with this object. And all instances of this prefab will have this value by default.


If you want all objects to share the value at runtime, then a static variable is a solution.

Or you can create a manager (a singleton object) that keeps track of all your object, so that it can change all values at once.

Or you can create a singleton that holds this value and all of your other objects read this value at runtime.