Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Dynamic variable reference?

Discussion in 'Scripting' started by ackley14, Jul 2, 2015.

  1. ackley14

    ackley14

    Joined:
    Oct 31, 2014
    Posts:
    31
    Hey! I was wondering if there's a good way to reference variables dynamically so i don't have to hardcode my entire console script with every single variable in my game lol
    i.e.

    user enters into console : Items.Iron_ingot.Quant 53

    then the variable: Items.Iron_Ingot.Quant now has the value of 53

    i can parse the text and sperate it just fine. my problem is executing it without having a catch for EVERY single variable within my game.

    note: i HATE using libraries from other developers for simple one off tasks like this. i prefer to do these kind of in-engine things myself so i don't have to deal with purchasing a library or hoping it gets updated to the latest version of unity so i can start working on my project again.

    thanks for any help!!!
     
  2. WheresMommy

    WheresMommy

    Joined:
    Oct 4, 2012
    Posts:
    890
    As far as I know, you cannot create dynamic vars out of the box. But you can use for example a Dictionary to store strings with a value. Not sure, if this is what you are looking for, but maybe this is the right approach:
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. using System.Collections.Generic;
    4.  
    5. public class DynamicVars : MonoBehaviour {
    6.     public Dictionary<string, int> list = new Dictionary<string, int>();
    7.  
    8.     // Use this for initialization
    9.     void Start () {
    10.         GenerateDynamicVars (5);
    11.     }
    12.  
    13.     void GenerateDynamicVars(int count){
    14.         for (int i=0; i<count; i++) {
    15.             string varName = (count + "" + i).ToString() ;
    16.             list.Add (varName, i);
    17.             Debug.Log(varName + " has value " + list[varName]);
    18.         }
    19.     }
    20. }
     
  3. Deleted User

    Deleted User

    Guest

    Unfortunately, dynamic is not currently supported.
    What exactly are you trying to achieve by letting a user type a variable name to set it's value? Is this for a game or an asset to be sold on the Asset Store?

    To answer your question, you can use reflection (System.Reflection) to get and set values from a class via a string.
    This question from StackOverflow may help you out in how to accomplish this:
    http://stackoverflow.com/questions/1089123/setting-a-property-by-reflection-with-a-string-value