- Home /
Adding variables from all scripts
Hi, I've got a few GameObjects with the same script in my scene. I'm trying to get the values from variables in that script and add them together. I don't really know how to accomplish this.
Any suggestions?
Answer by whydoidoit · May 25, 2012 at 04:58 PM
Well there are two methods. In the first your script adds a reference to itself to a static list of scripts in OnEnable and removes itself in OnDisable. Then you have an list of all of the scripts so its easy to work through them.
The other method involves using GameObject.FindObjectsOfType(typeof(GameObject)) - (C#) and then working through them getting the component from each if it exists. This method is slow.
Here's method 1 in C#
using System.Collections.Generic;
...
public static List<YourScriptClass> scripts = new List<YourScriptClass>();
void OnEnable()
{
scripts.Add(this);
}
void OnDisable()
{
scripts.Remove(this);
}
...
//In any class
foreach(var s in YourScriptClass.scripts)
{
//Do whatever
}
I don't really understand the first method. I'm in constant need of those variables, it's a number constantly displayed on the screen. What do the Enable and Disable functions do here?
Well OnEnable is called when the game object is activated and disable when it is deactivated or destroyed. $$anonymous$$g. When a new level is loaded or the object is drstroyed
So with method 1 you have an easy way of accessing every instance of your script from anywhere. You also ensure that you are only accessing living objects.
Think of OnEnable like Start but called each time the object is activated. It is obviously activated when it is instantiated or the game starts. After that it will only be called when the object is disabled (using active=false on the game object or enabled on the script) and the reenabled (active=true on game object or enabled on the script)
If you mean there is a variable on the script called myVariable, that it is public and you want something else to add them up then, also presu$$anonymous$$g that variable is a float, where you want to add it up you do this:
float total = 0;
foreach(var s in YourScriptClass.scripts)
{
total += s.myVariable;
}
Answer by DarkSlash · May 26, 2012 at 02:12 PM
I found a method that, may be is not the most elegant, but it saves my day:
On the main script I created a variable, lets say "flag" and I set it to false. When I want to change the variables from all objects, I just change the value of flag to true. In the object script, I just add a line to the Update function... if(OtherScript.flag == true) { ... } and that's it.
Heh if it works for you then fine. This kind of code can prove to be fragile however and hard to debug. I'd prefer a method of directly affecting the other scripts. For instance what sets that flag false and when? Is it possible that it will become false before all of the scripts have updated or perhaps some of the will update many times.