C#: Access variables of a class by string name

Hey Guys,
I’m currently trying to create a simple Minecraft Clone. I’ve created a Blocks Class containing all Blocks as static GameObject variables. Now I want to get the GameObject by using the string name of the variable. In Javascript (not UnityScript) you could do something like that:

function a() {
  this.x1 = "x";
  this.x2 = "y";
} 
console.log(new a()["x1"]) // output: x

I’ve tried out multible code samples from stackoverflow and others, but they didn’t work in Unity C#.

Here’s my Code of the Blocks Class:

using UnityEngine;
using System.Collections;

public class Blocks : MonoBehaviour {

	public static GameObject Dirt;
	public static GameObject Stone;

	public static GameObject AllBlocks;

	public static string[] getBlockList() {
		// return stringArray containing all blocks, for example: {"Dirt", "Stone"}
	}
	
	// Use this for initialization
	void Start () {
		Dirt = GameObject.Find ("Blocks/Dirt");
		Stone = GameObject.Find ("Blocks/Stone");

		AllBlocks = GameObject.Find ("Blocks");
		AllBlocks.SetActive (false);
		Debug.Log (getBlockList ());
	}
}

Thanks to anyone who can help!

Hmm… I think your aprouch is wrong here. It is possible to get a runtime field using Reflection but this comes with huge performance overhead. I suggest you create a class

[Serializable]
public class BlockDefinition
{
  public string name;
  public GameObject root;

  public IEnumerable<GameObject> GetChildren()
  {
    foreach(var child in root.transform)
   {
     yield return child.gameObject;
   }
  }
}

...
public class BlockController: MonoBehaviour
{
  public BlockDefinition[] allblocks;

  // Now configure it in the designer. 
  // Avoid using static unless you know what you doing, it will prevent your gameobjects from being freed
}

If all blocks are children of the same GameObject then you could simply check the name of every one. You could also investigate LINQ.

List<GameObject> dirt = new List<GameObject>
....

foreach(Transform child in transform){
    if(name == "Dirt"){
        dirt.Add(child.gameObject);    
    }
}