Home > Blockchain >  Out of range exception in Unity
Out of range exception in Unity

Time:01-07

I create a game in Unity. And I got this error:

System.ThrowHelper.ThrowArgumentOutOfRangeException (System.ExceptionArgument argument, System.ExceptionResource resource)

Here is my short code:

public class OnlineGame : MonoBehaviour
{
    private List<GameObject> domino = new List<GameObject>(7);

    public void Start()
    {
        StartGame();
    }

    private void StartGame()
    {
        for (int i = 0; i < 7; i  )
        { 
            domino[i] = Instantiate(dominoPrefab, new Vector3(11, 0, 0), Quaternion.identity) as GameObject;
        }
    }
}

If you need more details, write a comment. Thanks for help

CodePudding user response:

private List<GameObject> domino = new List<GameObject>(7)

new List<T>(int capacity) constructor doesn't mean the resulting list will have hold capacity objects at beginning. The Count of elements in the list will still be 0.

When you use List class in c#, it will have capacity memory reserved for the list. When you add some elements to the list and its Count reaches capacity(or close to it, I'm not exactly sure), the list will automatically increase capacity by allocating additional memory so that you can add additional element to the list.

Usually when you use new List<T>() the list will have initial capacity of 0 where program doesn't know how many Count the list can possibly have and will dynamically adjust capacity to match your need.

Using new List<T>(int capacity) is like telling the program that the list will have at most capacity number of elements and list should have that capacity ready to avoid overhead of allocating more memory. Of course, when list's Count reach capacity it will increase as well.

To fix your problem, use Add method instead of assigning to array slot.

public class OnlineGame : MonoBehaviour
{
    private List<GameObject> domino = new List<GameObject>(7);

    public void Start()
    {
        StartGame();
    }

    private void StartGame()
    {
        for (int i = 0; i < 7; i  )
        { 
            // domino[i] = Instantiate(dominoPrefab, new Vector3(11, 0, 0), Quaternion.identity) as GameObject;
            domino.Add(Instantiate(dominoPrefab, new Vector3(11, 0, 0), Quaternion.identity) as GameObject);
        }
    }
}
  •  Tags:  
  • Related