public class Button{
public bool free;
public Vector3 worldPos;
public Vector2 screenPos;
public int Type;
public Button(bool _free){
free = _free;
}
}
public class PlayerMobility : MonoBehaviour {
const int MaxBtn = 20;
Button[] Buttons = new Button[MaxBtn];
// Use this for initialization
void Start () {
//Buttons = new Button[MaxBtn];
for (int i = 0; i < MaxBtn; i++) {
print ("init");
Buttons[i].free = true;//<object reference not set to an instance of an object error
}
}
}
and I got: object reference not set to an instance of an object on line 22 I try digging online and cant seems to find any solution please help.
Well then the problem is clear. Button is not a struct but a class. That means its default value is null.
You must first create an instance of the class and assign it to the array index, before you can access it:
Buttons[i] = new Button(true);
Buttons[i].free = true; // A bit redundant since "free" is assigned in the constructor.
As Kwinten states, you need to create an instance for each item in your array. You can change your constructor so don’t have to pass a parameter if you like by giving it a default value;
public class Button
{
public bool free;
public Vector3 worldPos;
public Vector2 screenPos;
public int Type;
public Button(bool _free = false)
{
free = _free;
}
}
public class PlayerMobility : MonoBehaviour
{
const int MaxBtn = 20;
Button[] Buttons = new Button[MaxBtn];
// Use this for initialization
void Start()
{
//Buttons = new Button[MaxBtn];
for (int i = 0; i < Buttons.Length; i++)
{
Buttons[i] = new Button();
print("init");
Buttons[i].free = true;//<object reference not set to an instance of an object error
}
}
}