简体   繁体   中英

How to get local Object Variable using c#

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 ?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM