- Home /
Array Index out of range?
enter code here
I'm quite confused by this little issue. I've dealt with arrays and classes before, but clearly I've made some sort of mistake. I keep getting Array Index is out of range on the line:
Equip(AllSkills[0],0);
AllSkills, the Array of the class "Skill" has members in it... as does SkillSlot(Though I believe the out of range is refering only to AllSkills). I added these members in the inspector and they are filled out.
What is my mistake?
class Skill {
//Active or Passive
var Active : boolean;
//SkillObject
var TheObject: GameObject;
var CooldownCurrent : float;
var CurrentStamina : int;
var StaminaCost : int;
}
var AllSkills : Skill[];
var SkillSlot : Skill[];
function Equip ( NewSkill : Skill, Slot : int ) {
SkillSlot[Slot] = NewSkill;
if (!SkillSlot[Slot].Active) {
Instantiate (SkillSlot[Slot].TheObject,transform.position,transform.rotation);
}
}
function Activate ( Slot : int ) {
if (SkillSlot[Slot].CooldownCurrent == 0 && SkillSlot[Slot].StaminaCost < CurrentStamina ) {
if (SkillSlot[Slot].Active) {
Instantiate (SkillSlot[Slot].TheObject,transform.position,transform.rotation);
}
}
}
function Update () {
if( Input.GetKeyDown(KeyCode.Alpha1)) {
Activate(1);
}
if( Input.GetKeyDown(KeyCode.Alpha2)) {
Activate(2);
}
if(Input.GetKeyDown(KeyCode.T)) {
Equip(AllSkills[0],0);
}
}
Answer by robertbu · Oct 26, 2013 at 12:44 AM
AllSkills is never initialized in this code. It is a public variable, so the Inspector will create it for you at a size of 0. With a size of 0, any access you attempt will generate an index out of range. To fix it, you can either go the inspector and set the size of the array, or you can allocate space for teh array in code. If you do the latter, then you probably should make the array 'private'.
If it is filled in the inspector, the next check should be to see how many game object have this script attached. You can use the search field at the top of the Hierarchy view. This problem will occur if you have it attached to more than one game object and have only initialized one of those objects.
I'm on shaky ground here but it doesn't appear that your skills class is serializable. I don't know how Unity handles the size of an array pointing to non-searializable objects.
http://docs.unity3d.com/Documentation/ScriptReference/Serializable.html
This is the only object with it attached, but it would not matter if it wasn't. It shouldn't need to be serialized, based on my memory of using classes in the past, however Its worth looking into, I suppose, since I haven't touched them in a few months.
No; Serializing it would not effect it in the slightest.
Your answer
Follow this Question
Related Questions
Arrays rebels to my power! 1 Answer
Array Index Out of Range 2 Answers
OnGui function - Array is out of index question 1 Answer
Index out of range exception - C# - Can't find the problem 1 Answer
Array index is out of Range!? 1 Answer