- Home /
Class Array referencing
I keep getting this "IndexOutOfRangeException: Array index is out of range. grassPlain.createHandlerEntry () (at Assets/Scripts/Tiles/Grass/grassPlain.cs:32) grassPlain.Start () (at Assets/Scripts/Tiles/Grass/grassPlain.cs:21)"
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class grassHandler : MonoBehaviour {
public class glassPlain {
public bool isOwned;
public bool isBuilt;
public bool isPlagued;
public int population;
}
public grassPlain[] plain;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class grassPlain : MonoBehaviour {
// Handler Information
public bool hasEntry;
public int tileNumber;
public bool isOwned;
public bool isBuilt;
public bool isPlagued;
public int population;
// Script Information
public grassHandler grassHandler;
// Use this for initialization
void Start () {
createHandlerEntry ();
}
// Update is called once per frame
void Update () {
}
void createHandlerEntry () {
tileNumber = grassHandler.plain.Length + 1;
grassHandler.plain = new grassPlain[tileNumber];
grassHandler.plain [tileNumber].isOwned = false;
grassHandler.plain [tileNumber].isBuilt = false;
grassHandler.plain [tileNumber].isPlagued = false;
grassHandler.plain [tileNumber].population = Random.Range (0, 100);
Debug.Log (grassHandler.plain [tileNumber]);
}
}
Any help would be appreciated, I've tried several different ways but I always end up with the same result, arrays and raycasting have been my struggles of late.
Answer by nug700 · Mar 05, 2017 at 03:47 AM
grassHandler.plain = new grassPlain[tileNumber];
Is not going to initialize the objects in the array. You will get a NullreferenceException on the next line, even without the IndexOutOfRangeException. The IndexOutOfRangeException would be solved by using grassHandler.plain [tileNumber - 1].isOwned = false;
after grassHandler.plain = new grassPlain[tileNumber];
, you would do grassHandler.plain[tileNumber - 1] = new grassPlain();
Also, you do not need to add 1 to the length. This would actually add 2 to the array length. You could also use a List ins$$anonymous$$d of an array. a List contains an Add(obj) method to add things. https://msdn.microsoft.com/en-us/library/6sh2ey19(v=vs.110).aspx
This is exactly what I was looking for, and I didn't even know, thanks.
Your answer
Follow this Question
Related Questions
Need my function to work with different lists of different values (classes) 1 Answer
Instantiating objects from a class? (C#) 1 Answer
How to access individual class elements, that has an array, that is in a list for c# 1 Answer
Wierd IndexOutOfRangeException : Array index is out of range 1 Answer
IndexOutOfRangeException: Array index is out of range. 1 Answer