Looping through generic list and comparing index with random number?

I want to iterate through a generic list and compare the current index with a random number. The code below doesn’t run as it tries to compare type Door with type Int. I want to compare the index position (integer?) with an integer number, not the type itself. Any help is appreciated!

public Door door;
public Vector3 pos;
public List<Door> doors = new List<Door>();

...

Door newDoor = Instantiate (door, pos, Quaternion.identity) as Door;
doors.Add(newDoor);

...

int num = Random.Range (0, doors.Count);
for (int i = 0; i < doors.Count; i++) {
    if (doors[i] == num) {
        // Do this
    }
}
if(i == num) {
    // Do this
}
2 Likes

Is that it? Oh god do I feel stupid now haha. Thank you! :slight_smile:

Or…don’t loop at all?

doors[num]
3 Likes

That’s … even better. To add to my question, I want to change these two variables of the instantiated door in my list at the position num. However, I can’t for the life of me figure out how to do that.

I would want to write door[num].doorTag = “something” but that doesn’t work, I seem only to be able to change the variables for the class itself, not the instantiated object.

public class Door : MonoBehaviour(){

    public string doorTag;
    public bool isTagged;

}

You’re trying to change the tag on the GameObject?

doors[num].gameObject.tag = "something";
1 Like

I am trying to change my custom variables that the GameObject inherits from my custom class, but only on that instantiated GameObject in index position num. That variable is a string called doorTag, not the tag on the GameObject (confusing variable names on my part).

Then what you wrote should work fine.

1 Like

Just got home and tried it. Thank you very much! :slight_smile: