- Home /
"Object reference not set to an instance of an object" problem
Hello. I am fixing my code. I want it to be more optimised and not to be attached to gameObjects. I am getting an error : "Object reference not set to an instance of an object". I know what this problem means, but I do not know how to fix it. How can I receive my GameObjects from the place where I store them?
The place where problem occurs:
public void create ()
{
//The problem***
Digger = GameObject.Instantiate (Storage._Digger) as GameObject; //***
}
private _Storage Storage; //See below
private GameObject Digger;
The _Storage class, where GameObjects are attatched to:
public class _Storage : MonoBehaviour
{
public GameObject _Digger;
}
And the Main class, where Start() and Update() functions are done:
public class _Main : MonoBehaviour
{
void Start ()
{
MainDigger.start ();
}
void Update ()
{
MainDigger.update ();
}
private DiggerMovement MainDigger = new DiggerMovement();
}
NullReferenceException: Object reference not set to an instance of an object DiggerMovement.start () (at Assets/Scritps/DiggerMovement.cs:9) _Main.Start () (at Assets/Scritps/_Main.cs:9)"
Thanks
Answer by Dainiusss · Feb 15, 2015 at 03:58 PM
Sorry for double post, but I solved this problem with little help and want to share the result, if someone will have the same issue in the future. I don't know if anyone will find this helpful, but anyways... sharing is caring. Also, if someone has any advice, it would be appreciated.
My storage class:
public class _Storage : MonoBehaviour
{
public GameObject _Digger;
}
My object class (the same where the problem was):
public class DiggerMovement
{
public void SetStorage(_Storage s)
{
Storage = s;
}
public void start ()
{
Digger = GameObject.Instantiate (Storage._Digger) as GameObject;
}
public void update()
{}
private _Storage Storage;
private GameObject Digger;
}
My main class (where all the actions are done):
public class _Main : MonoBehaviour
{
void Start ()
{
_Storage s = GameObject.Find ("Storage").GetComponent<_Storage> ();
MainDigger.SetStorage (s);
MainDigger.start ();
}
void Update ()
{
MainDigger.update ();
}
private DiggerMovement MainDigger = new DiggerMovement();
}