Array stores Text GameObjects

I have 10 Text objects tagged with “1stThrow”, 10 tagged with “2ndThrow”, and 10 tagged with “culScore”. I use the following lines of code to access these Text objects in my Unity project:

csharp

Copy code

GameObject[] firstThrowObj;
public Text[] firstThrow;
GameObject[] secondThrowObj;
public Text[] secondThrow;
GameObject[] totalObj;
public Text[] totalscore;

void Start()
{
    firstThrowObj = GameObject.FindGameObjectsWithTag("1stThrow");
    firstThrow = new Text[firstThrowObj.Length];
    for (int i = 0; i < firstThrowObj.Length; i++)
    {
        firstThrow[i] = firstThrowObj[i].GetComponent<Text>();
    }

    secondThrowObj = GameObject.FindGameObjectsWithTag("2ndThrow");
    secondThrow = new Text[secondThrowObj.Length];
    for (int i = 0; i < secondThrowObj.Length; i++)
    {
        secondThrow[i] = secondThrowObj[i].GetComponent<Text>();
    }

    totalObj = GameObject.FindGameObjectsWithTag("culScore");
    totalscore = new Text[totalObj.Length];
    for (int i = 0; i < totalObj.Length; i++)
    {
        totalscore[i] = totalObj[i].GetComponent<Text>();
    }
}

Issue:

When I try to update the text in the HandleFirstThrow method using the line:

csharp

Copy code

firstThrow[throwCounter].text = throw.ToString();

I receive an “IndexOutOfRangeException” error.

Do you see the counter’s value? (maybe print it out right before this?)

It changes every time the player roll the ball

Yes, but at some point it may have a value that is out of range. So if you know what it is, maybe you can track the issue… I am just talking as an old-fashioned programmer, I don’t work with Unity (soon, but not yet) :wink:. If the log around the exception does not clarify much, I would just print the value every single time it’s about to use it and see what comes out.

The scoreboard is currently inactive and can only be accessed through a button, which is why the array is unable to reference the text elements on the board

1 Like

Privacy & Terms