How to find a struct variable with a string

Hi there,

I have a string wich is given a value by another script.(this name is equal to 1 of the struct variable names) and
I have a struct wich stores 3 variables called: strenght, constitution and agility(these are all an int)

What I want is next:
I want to pick 1 of the struct variables with my string so that I can change the value of 1 of the struct variables.
I have tried dictionary but I dont understand (a rabbit turd)/anything of it.

I appreciate any help :slight_smile:

If it’s long lived it shouldn’t be a struct in the first place, it should be a class. Classes are more performant and provide you with easier ways to set variables by reflection.

     using System.Reflection;

     public class ReflectableClass  {

          public object this[string key] {
                 get {
                      return this.GetType().GetField(key, BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic).GetValue(this);
                 set {
                      this.GetType().GetField(key,BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic).SetValue(this, value);


Then your class looks like this:

     public class Attributes : ReflectableClass {
            public int strength;
            public int agility;

And you can access it like this:

      var instance = new Attributes();
      instance.strength = 10;   //Both update strength
      instance["strength"] = 20;

Dictionaries aren’t so hard to use. The way they work is you determine which datatype you will like to use for the keys and which datatype you would like to use for the values.

You set it up like this:

// The dictionary to store the information in
	public Dictionary<string, int> dictionary = new Dictionary<string, int>();

This dictionary uses string for keys and int for values. The data in the dictionary is as key:value pairs, where you only need to know the key to retrieve the value from the dictionary. Here is an example of storing three different key:value pairs and retrieving them.

// Use this for initialization
void Start () {
	// Add values to the dictionary under different keys.
	dictionary.Add("Strength", 100);
	dictionary.Add("Constitution", 50);
	dictionary.Add("Agility", 75);

	// Retrieve values by their key.
	int strengthValue = dictionary["Strength"];
	print("StrengthValue: "+strengthValue);
	print ("Constitution: "+dictionary["Constitution"]);
    print("Agility: "+dictionary["Agility"]);

This should do it:

int value = typeof(Struct).GetProperty("propertyName");