Global variable for all clones

I have prefabs splawning through time. Each prefab has attached script.
In this script i have:

    public bool isAffected;

I want this var to be common for all instances. I know I can use some other script attached to the unique object in the scene to store “shared” vars, but I feel there’s some easier way to make the variable global\common\shared for all prefabs with the same script attached.

@exe2k - Hi.

“I want this var to be common for all instances.”

You can make your isAffected static - it will be part of class, not you objects.

Not sure how this makes sense, but like this:

public static bool isAffected;

Potentially problematic: static fields won’t show up in inspector…

1 Like

Thank you! Idk but i tried this before and that didn’t worked for some reason…now it’s ok.

Static is one answer. Its a fairly inflexible one though.

If you need something more sophisticated, you could create a reference on all of the instances that points to the same object.

Do you mean that you want the value of isAffected to be synchronized between all instances of your prefabs?

I would create a class like MyPrefabGroup that contains the isAffected variable. When you instantiate the objects, they get added to the group, and can access the group’s properties. If you change isAffected on the group, all the objects will read the new value.

Does this have a memory hit, or other consequences? It solves my problem, but I want to use it a lot, like thousands of times.

None worth mentioning. The reference will probably about the same size as an int or a bool- probably around 4 bytes.

1 Like

Thousands of times in what respect? Thousands of variables, or thousands of calls to one variable? Or thousands of references to the variable in your code?

Not that you’ll notice.

1 Like

Thousands of references to the variable/object, each reference in a different object (kind of like particles that know about another object)

This isn’t explicitly true in C#, but a reference is effectively just a piece of data that points to another memory address to read from. It doesn’t matter how many times that piece of data shows up in the RAM. For your purposes there is no difference from where in the RAM you request that memory read vs where the data actually is in RAM.