- Home /
Index Out Of Range Exception, Why i am getting this error?
Please help me. I am getting the following error four times, 'coz the loop is running for the four times: Index out of range exception: Index was outside of the bounds of the array.
This is my script:
public class enemySpawn : MonoBehaviour { public GameObject enemySpawnee; public GameObject playerObject;
float InstantiationTimer = 2f;
float xPos, yPos;
Player playerScript;
[HideInInspector]
public int actualCount = 0;
[HideInInspector]
public bool[] spawnEnable= { true, true, true, true};
private void Start()
{
playerScript = playerObject.GetComponent<Player>();
Debug.Log(spawnEnable.Length);
/*
for (int i = 0; i < 4; i++)
{
spawnEnable[i] = true;
}*/
}
void Update()
{
if(spawnEnable[0])
{
CreatePrefab1();
}
if (spawnEnable[1])
{
CreatePrefab2();
}
if (spawnEnable[2])
{
CreatePrefab3();
}
if (spawnEnable[3])
{
CreatePrefab4();
}
}
private void OnTriggerExit(Collider collider)
{
if (collider.gameObject.tag == "Player")
{
if (playerScript.quaderentCheck == 1)
{
spawnEnable[0] = true;
}
if (playerScript.quaderentCheck == 2)
{
spawnEnable[1] = true;
}
if (playerScript.quaderentCheck == 3)
{
spawnEnable[2] = true;
}
if (playerScript.quaderentCheck == 4)
{
spawnEnable[3] = true;
}
}
}
void CreatePrefab1()
{
InstantiationTimer -= Time.deltaTime;
if (InstantiationTimer <= 0)
{
if(actualCount < 5)
{
xPos = Random.Range(-65, -3);
yPos = Random.Range(22, 3);
Instantiate(enemySpawnee, new Vector3(xPos, yPos, 10), Quaternion.identity);
}
InstantiationTimer = 2f;
actualCount++;
} }
void CreatePrefab2()
{
InstantiationTimer -= Time.deltaTime;
if (InstantiationTimer <= 0)
{
if (actualCount < 5)
{
xPos = Random.Range(6, 65);
yPos = Random.Range(22, 3);
Instantiate(enemySpawnee, new Vector3(xPos, yPos, 10), Quaternion.identity);
}
InstantiationTimer = 2f;
actualCount++;
}
}
void CreatePrefab3()
{
InstantiationTimer -= Time.deltaTime;
if (InstantiationTimer <= 0)
{
if (actualCount < 5)
{
xPos = Random.Range(-65, -3);
yPos = Random.Range(-4, -24);
Instantiate(enemySpawnee, new Vector3(xPos, yPos, 10), Quaternion.identity);
}
InstantiationTimer = 2f;
actualCount++;
}
}
void CreatePrefab4() {
InstantiationTimer -= Time.deltaTime;
if (InstantiationTimer <= 0)
{
if (actualCount < 5) {
xPos = Random.Range(6, 65);
yPos = Random.Range(-4, -24);
Instantiate(enemySpawnee, new Vector3(xPos, yPos, 10), Quaternion.identity); }
InstantiationTimer = 2f;
actualCount++;
}} }
@Hellium @Eric5h5 @clunk47 @Bunny83 @robertbu @aldonaletto @tanoshimi
Hey, this code works in my project. By the way, you can also use public bool[] spawnEnable = {true, true, true, true};
. Looks like maybe something didn't initialize in your case? Did you try debugging it? Are you sure the error is related to this line of code? spawnEnable[i] = true;
Thank you, yes i tried to debug it, but it was fine. Yes error is co$$anonymous$$g out of every line where i am using spawnEnable[]. I tried the method you have mentioned above but i am still getting the same error. And i do not know what is wrong with my script. When i tried to check the length using: Debug.Log(spawnEnable.Length) not only it is giving me output - "0" but it is showing this four times even though i have put it in Start().
How many gameObjects with this script attached do you have on your scene? And, could you show us whole script?
Answer by Siljias · Jun 26, 2020 at 05:28 AM
In your update loop, you are accessing the array with, "1,2,3,4". However, due to how array indexing works, you need to use "0,1,2,3".
spawnEnable[0] -> first element
spawnEnable[1] -> second element
NOT
spawnEnable[1] -> first element
spawnEnable[2] -> second element
I did not see anything in your start function that would throw that error. The update loop will definitely throw it tho.
EDIT
Your OnTriggerEnter() callback is also trying to access the array indices, starting with 1. That will probably also throw an error, once it gets to the last option.
That was really silly of him, thank - you for pointing out. But error still persists sir.
@nikhilVardhan Let us know in which line the error occurs. Did you enable "Clear on play" in Console?
$$anonymous$$ake sure to change it in the OnTriggerExit() callback as well. And make sure all four options are changed, not just the first two that I wrote in the answer ;P
Answer by ilusja · Jun 26, 2020 at 05:32 AM
During the investigation of the code, I've discovered the thing:
you're using
if (spawnEnable[4])
{
CreatePrefab4();
}
in your Update()
fuction. When you're getting an error, check in which line the error occurs (in my case, it says IndexOutOfRangeException: Index was outside the bounds of the array. EnemySpawn.Update () (at Assets/EnemySpawn.cs:46)
). Also, you could read about how to debug your code, this will prevent this kind of problems in the future.
spawnEnable
length is 4
, this means you can access spawnEnable[0]
(first element in the array) and spawnEnable[3]
(last element), but not spawnEnable[4]
. This is outside the bounds of the array.
As a side note, I would add [RequireComponent(typeof(Collider))]
to your script and rename the class to EnemySpawn
. You should avoid using small letters at the beginning of your classes names, usually PascalCase is used.
Please, let me know if it solved your problem :)
No, in my case it started to pointing out from: if(spawnEnable[0]) // i corrected the code after @Siljias pointed out { createPrefab1(); }
Ok, try to turn Unity off, and delete:
projectpath/*.sln,
projectpath/*.csproj,
projectpath/Temp,
projectpath/obj,
projectpath/Library/ScriptAssemblies,
turn the Unity on again and press play.
Answer by Jon_Olive · Jun 27, 2020 at 07:49 PM
I have a feeling what might have happened is that you initially just declared the spawnEnable array without assigning a length or values and perhaps added those later. That would mean that it got serialised as an empty array of length zero - after which adding the hard coded values would have had no effect.
Do you actually need to serialise spawnEnable - or just have it be public? if the latter - replace [HideInInspector] with [NonSerialized] - it will still be public but wont show in the inspector and will not get serialised.
I have solved this but it's still a not precise solution. What actually happened is, the variable was just a normal int variable initially, afterwards, i needed an array ins$$anonymous$$d so i changed the same variable to array. And that's why this whole thing has happened, the same thing is happened with an another variable when i changed it to an array. I don't know why this is happening, its like unity and studio are not in sync.
sounds like a Unity serialization bug then rather than an issue between unity and studio - it's getting confused when you keep the same variable name. I just tried it and indeed in both my scenario and yours you get the behaviour you experienced. Commenting out the variable declaration, letting unity recompile the script and then uncommenting sorts it out.