|
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
(comments are locked)
|
|
If you want a variable to be defined on all objects, define it static: JS: C# 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. You need a script called 'GlobalVariables' and you need to assign it in the inspector once you've created the object. Ok,I am using global variable now. let's say there are two scripts in one scene,I have a static variable declared in script 1 , and I need to use that variable in script 2. In script 2 , it reads the variable,no error occurs , but it's giving me Null value? Why is it like that?
Feb 01 '12 at 03:24 AM
071813g
Well, null values can happen if the value has never been assigned. Make sure that if the object is a reference type, it is guaranteed to always have an instance.
Feb 01 '12 at 03:26 AM
syclamoth
I did what it's told from this link: (at the bottom of the page)
Feb 01 '12 at 03:31 AM
071813g
Waaait, are they two instances of the same script, or are they two different scripts?
Feb 01 '12 at 03:34 AM
syclamoth
I have assigned the value in script 1 , but it just doesn't have any value in script 2. What do you mean by the object is a reference type?
Feb 01 '12 at 03:35 AM
071813g
(comments are locked)
|
|
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. Thanks for your response. I forget to mention that I want is that one variable can be shared between two scripts. So does that mean I need to create a singleton that holds all the global variables and other scripts can get reference from it?
Feb 01 '12 at 03:29 AM
071813g
(comments are locked)
|
