Why does IndexOf not return the right index?
for (int i = 0; i < playerList.Count; i++)
{
Debug.Log("For Loop Index: " + i);
var player = playerList[i];
Debug.Log("Is this the index:" + playerList.IndexOf(player));
}
Hey! So I ran this loop in a LateUpdate(), because I need a text prefab to be attached to a player GameObject, and when I ask the index of the player which was fetched by the "i = 0" index, he gives me back "0", but when I ask the index of the player which was fetched by the "i = 1" index, he gives me back "0" again! Does anyone know why and what I can do?
Answer by Vicarian · Jul 02, 2018 at 04:22 PM
It's not returning an incorrect index at all. You don't have any logic to differentiate the player from the values in the array, so you're actually going to receive log statements in the quantity 2 * playerList.Count ^ playerList.Count. It may not appear that way if you have message collapsing enabled on your console, but it's there. In other words, it's simply printing two statements for each player for each player.
Okay, but I don't have collapsing, it is not showing as you can see by the photo and what do you mean by "for each player for each player"?
It means that for every player in your array, assu$$anonymous$$g this script is attached to a player and there are multiple players, it will run that loop for each of them, for however many players there are.
Yeah, but I'm not in the console of all the players, just one. And that doesn't change the fact that I'm still not seeing the right index... Also, the playerList is filled by GameObjects with the tag "Player" in the scene and this script only spawns for the local player and not across the network.
Hey @Vicarian you're right, I checked the content of the list on runtime with 2 players, and it referenced the local player twice, so that's a while other problem (that I would appreciate some help with :) ), but thanks anyway!