How can I reach to a variable by dinamically created name

Hi all,
I think this is what they say reflection.
Lets say I have 3 variables
GameObject Object1;
GameObject Object2;
GameObject Object3;
I want to get position of 3 objects randomly
how can I say something like this

MyVariable.name(“Object”+UnityEngine.Random.Range(1,4)).transform.position

GameObject Mekan = this.GetType().GetField("Mekan" + UnityEngine.Random.Range(1, 6).ToString()).GetValue(this) as GameObject;

You’ve solved this with reflection, but that is a pretty poor solution here. It will not be very performant, and as you can see, the code is a mess.

The better option, whenever you find yourself with variables that have “numbered” names, is to simply use an array:

public GameObject[] myObjects;

void Start() {
  GameObject randomObject = myObjects[Random.Range(0, myObjects.Length)];
  Vector3 position = randomObject.transform.position;
}

I searched and found my solution to get rid of arrays. That is why I like reflection.

Anyone disagrees with Jonathan Blow on the state of game and software development just show them this thread.

2 Likes

the main reason that Blow is known as the best indie, is the 7 years age difference between him and me.