- Home /
Need help setting an array of my class
So I want to make an array that hase objects of a class gun in it .
[System.Serializable]
public class gun
{
public string name;
public float damageGiven;
public string type;
public float firerate;
public int magazineSize;
public int bulletS;
public gun (string _name , float _damageGiven , string _type , float _firerate , int _magazineSize , int _bulletS)
{
name = _name;
damageGiven = _damageGiven;
type = _type;
firerate = _firerate;
magazineSize = _magazineSize;
bulletS = _bulletS;
}
}
this is my class
void Start()
{
public gun[] guns = new gun[10];
guns [0] = new gun ("pistol", 25, "pistol", 0, 50, 50);
}
but when I launch the game it says
IndexOutOfRangeException: Array index is out of range. (wrapper stelemref) object:stelemref (object,intptr,object)
at a guns [0] part of code .
any help
That shouldn't even compile, but I assume you've posted snippets.
The 'public' declaration for guns isn't 'legal' within a function. I assume you mean that the public declaration for guns is a member of a class. The start method you've entitled as your class isn't a class, it's a member function, but I can't tell what class it is in.
That said, if you have actually performed the allocation of guns as depicted (where I assume the code should actually be placed), there is no reason for an out of range exception.
That tells me the code isn't as you've posted, so I'd need to see what you have actually written, not what this edited posts suggests you think you wrote.
Since your array guns is public, are you sure that you didn't accidentally set it's size to 0 in the inspector?
It would also be nice if the other parts of your code actually made sense.