Search Unity

  1. We are migrating the Unity Forums to Unity Discussions. On July 12, the Unity Forums will become read-only. On July 15, Unity Discussions will become read-only until July 18, when the new design and the migrated forum contents will go live. Read our full announcement for more information and let us know if you have any questions.

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

Discussion in 'Scripting' started by PinwheelPlanet, Feb 29, 2024.

  1. PinwheelPlanet


    Jul 9, 2020

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

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

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

    Thanks :)
  2. PraetorBlue


    Dec 13, 2012
    Sure first you'd make a class for your variable:
    Code (CSharp):
    1. [Serializable]
    2. public class DynamicVariable {
    3.   public string name;
    4.   public float value;
    5. }
    Then you could for example allow an array of those to be created in a MonoBehaviour script:
    Code (CSharp):
    1. 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:
    Code (CSharp):
    1. public DynamicVariable[] myVariables;
    2. Dictionary<string, DynamicVariable> dict = new();
    4. void Awake() {
    5.   foreach (var variable in myVariables) {
    6.     dict[] = variable;
    7.   }
    8. }
    10. public float GetVariableValue(string variableName) {
    11.   return dict[variableName].value;
    12. }
    Nad_B and spiney199 like this.
  3. SisusCo


    Jan 29, 2019
    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.
    CodeRonnie, PraetorBlue and Nad_B like this.