Question by
DmitryLovin · Feb 14, 2017 at 04:18 AM ·
errorgameobjectindexoutofrangeexception
Unity C# array index is out of range
Having trouble with array of GameObjects.
a piece of code:
private string[] weap = new string[] {"p_01","smg_01","sg_01"};
public GameObject[] guns;
void Start () {
guns[0] = Resources.Load("Prefab/weapons/" + weap[0], typeof(GameObject)) as GameObject;
guns[1] = Resources.Load("Prefab/weapons/" + weap[1], typeof(GameObject)) as GameObject;
guns[2] = Resources.Load("Prefab/weapons/" + weap[2], typeof(GameObject)) as GameObject;}
And error:
IndexOutOfRangeException: Array index is out of range. (wrapper stelemref) object:stelemref (object,intptr,object) init.Start () (at Assets/Resources/script/init.cs:23)
line 23: guns[0] = Resources.Load("Prefab/weapons/" + weap[0], typeof(GameObject)) as GameObject;
I have no ideas why I have this error =(
Comment
Best Answer
Answer by DmitryLovin · Feb 14, 2017 at 04:30 AM
nvm, I fixed this. At first, only
public GameObject[] guns = new GameObject[3];
doesn't works.
It start working only with
public GameObject[] guns = new GameObject[3];
void Start () {
guns = new GameObject[] {
Resources.Load("Prefab/weapons/" + weap[0], typeof(GameObject)) as GameObject,
Resources.Load("Prefab/weapons/" + weap[1], typeof(GameObject)) as GameObject,
Resources.Load("Prefab/weapons/" + weap[2], typeof(GameObject)) as GameObject};
But I still don't know why.
Your answer
Follow this Question
Related Questions
NullReferenceException: Object reference not set to an instance of an object 0 Answers
One script with multiple Gameobject only one Works 0 Answers
Array index is out of range (C#)? 1 Answer
Unity bug gives false error messages or doesen't work without a Debug.Log() line present 1 Answer
Serialization depth limit exceeded at 'MaterialNode' error 0 Answers