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?

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 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.