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

    PinwheelPlanet

    Joined:
    Jul 9, 2020
    Posts:
    1
    Hello,

    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).
    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:
    upload_2024-2-29_20-14-30.png

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



    Thanks :)
     
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,960
    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();
    3.  
    4. void Awake() {
    5.   foreach (var variable in myVariables) {
    6.     dict[variable.name] = variable;
    7.   }
    8. }
    9.  
    10. public float GetVariableValue(string variableName) {
    11.   return dict[variableName].value;
    12. }
     
    Nad_B and spiney199 like this.
  3. SisusCo

    SisusCo

    Joined:
    Jan 29, 2019
    Posts:
    1,393
    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.