questionasker
questionasker

Reputation: 2697

How to get local Object Variable

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 ?

Upvotes: 0

Views: 642

Answers (1)

questionasker
questionasker

Reputation: 2697

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);

Upvotes: 1

Related Questions