0

Currently i develop something in Unity using C#.

Let's say i have define below variable, these script is in same file and Orange is Prefab :

private GameObject orange;
private GameObject avocado;

then, i want to access/get it's Object by Name/String (Because future development will using many Dynamic Variable) , i have tried it using GetType() but no luck, for example :

void Awake() {

orange = (GameObject)Resources.Load ("fruits/Orange", typeof(GameObject)); //getting Orange Prefab
avocado = (GameObject)Resources.Load ("fruits/Avocado", typeof(GameObject)); //getting Avocado Prefab

}  

void Start() {

//Here, i try to get orange/avocado/other fruitname by string
GameObject orangeObj = (GameObject) this.GetType().GetField("orange").GetValue(this); 

GameObject _orange = Instantiate ( orangeObj, new Vector3 (elem_1_pos_x, elem_1_pos_y, 0), Quaternion.identity) as GameObject;

}

Above code will give me error : "Object Reference not set to an instance of an object" which means it still not getting the orange object.

Any Idea or Suggestion ?

derHugo
  • 83,094
  • 9
  • 75
  • 115
questionasker
  • 2,536
  • 12
  • 55
  • 119
  • @RomanoZumbé i try to Read/Access `Orange Prefab` by string, but if you have better method please let me know... – questionasker Jul 22 '17 at 05:43
  • @RomanoZumbé can't be like that. in `Start()` method, i want to get Orange `GameObject` by string. In Future, it will be dynamic. i.e "grape", "avocado", etc... – questionasker Jul 22 '17 at 05:49
  • `GetField` only gets public static and instance fields by default. You need to specifically tell it to look for private fields: https://stackoverflow.com/questions/95910/find-a-private-field-with-reflection/95973#95973 – 31eee384 Jul 22 '17 at 05:57
  • Hi @31eee384 i got it, but how to convert `FieldInfo` to `GameObject` ? – questionasker Jul 22 '17 at 06:10
  • You already have the code for that in your question. – 31eee384 Jul 22 '17 at 06:13
  • Hi @31eee384 amazing, it solved :) This save me hours... you can write your answer, so i can say thanks... – questionasker Jul 22 '17 at 06:18

1 Answers1

1

By Suggestion in Questions's comment. I found an answer, Change :

GameObject orangeObj = (GameObject) this.GetType().GetField("orange").GetValue(this); 

to

GameObject orangeObj = (GameObject) this.GetType().GetField("orange", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(this);
questionasker
  • 2,536
  • 12
  • 55
  • 119