How to add a dynamic variable from Inspector (with +), to be used all over my scripts?

Hello,

So I am trying actually two things, maybe you have one suggestion (or two :smile: )

So first, is there possible to declare one variable into inspector, in one script, and check that in another script (to be related to the name).
9672434--1378142--upload_2024-2-29_20-10-33.png
And this abc to be checked in another script.
With if(abc = true) or something… to do something else.

I want to put the same script on a lot of GameObjects. And when one trigger will be detected on these objects, that variable to be created.

And in another script, to specify also that variable (in the same way as above), and to check that, if it is true/false or whatever.
Or how you suggest to do that?

Also, the second thing. Is this possible to add with one + botton?
Like this:
9672434--1378145--upload_2024-2-29_20-14-30.png

So to add or to remove those fields in order to declare my variables there.

Thanks :slight_smile:

Sure first you’d make a class for your variable:

[Serializable]
public class DynamicVariable {
  public string name;
  public float value;
}

Then you could for example allow an array of those to be created in a MonoBehaviour script:

public DynamicVariable[] myVariables;

If you want them to be able to be looked up quickly you could throw them in a Dictionary and provide an accessor method for example:

public DynamicVariable[] myVariables;
Dictionary<string, DynamicVariable> dict = new();

void Awake() {
  foreach (var variable in myVariables) {
    dict[variable.name] = variable;
  }
}

public float GetVariableValue(string variableName) {
  return dict[variableName].value;
}
2 Likes

You could use scriptable object variables for this.

Using just raw strings is quite dangerous, because it’s easy to end up in a situation where deleting or renaming variables can cause various prefabs and scene objects to break without any warning.

3 Likes