Index Error

devomage

Member
Getting an intermittent index out of range error on line #178

n = 14

C#:
private void ShuffleSpawnPoints(List<SpawnPoint> spawnPoints)
{
    var n = spawnPoints.Count;
    while (n > 1) {
        var k = Random.Range(0, n);
        var temp = spawnPoints[n];
        spawnPoints[n] = spawnPoints[k];   // line #178 of SpawnPointManager.cs
        spawnPoints[k] = temp;
    }
}
 
This works. I had to replace 'while' with 'if'. Unity was freezing using the former with the same code.

My first thought is something else is causing this to error... only because it seems this error would have popped up for others. Maybe something to do with the (SpawnPointManager) Instance in networking? My first spawned character is ok. The second spawn triggers the error.

C#:
if (n > 1)
{
    var k = Random.Range(0, n);//n - 1 here?
    var temp = spawnPoints[n-1];

    //Debug.Log($"n={n} k={k} null={temp == null}");
    //n=14 k=10 null=False

    spawnPoints[n-1] = spawnPoints[k];
    spawnPoints[k] = temp;
}
 
Last edited:
Thanks for letting me know. You should be able to fix this by adding n-- within the loop. It does need to loop instead of being an if statement so it shuffles all of the spawn points.
 
Top