A
A
Anton Vertov2018-05-30 00:53:41
C++ / C#
Anton Vertov, 2018-05-30 00:53:41

Why IndexOutOfRangeException: Array index is out of range?

Good day. I get the error IndexOutOfRangeException: Array index is out of range, but I don’t understand why.
Here is the code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Gameplay : MonoBehaviour {

    string Word;
    public GameObject PrefabCharCell;
    public GameObject[] tempCell;
    public Transform GridCellPos;
    
  void Start ()
    {
        Word = "Meet"; 

        foreach (char ch in Word.ToUpper().ToCharArray())
        {
            for (int i = 0; i < Word.Length; i++)
            {
                tempCell[i] = Instantiate(PrefabCharCell);
                tempCell[i].transform.SetParent(GridCellPos, false);
            }
    }      
    }
}

I want to save each created object to the tempCell array in order to work with them (objects) later, but an error is thrown IndexOutOfRangeException: Array index is out of range, that I go beyond the array, but why?
Please tell me how to solve the problem? Or an alternative way how to work with created objects (arrays) through a script. Thank you very much in advance!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
EVGENY T., 2018-05-30
@1Frosty

It is necessary to allocate memory for the tempCell array
tempCell = new GameObject[Word.Length];

S
Suren, 2018-05-31
Jagaryan @saylar

for (int i = 0; i < Word.Length - 1; i++)
Try this

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question