- Home /
Object Inheritance NullReferenceException: Object reference not set to an instance of an object
0 I have a script called GreedySearch where it contains the following function printMove().
public class GreedySearch : MonoBehaviour {
public void printMove(){
Debug.Log ("GS printMove()");
}
}
Now I have a main controller called EnemyBrain which defines the following like this:
public class GreedySearch : MonoBehaviour {
public GreedySearch gSearch;
public virtual void Start () {
gSearch = GetComponent<GreedySearch> ();
}
public void moveNPC() {
gSearch.printMove();
}
}
Now I have a Enemy script that inheritance EnemyBrain, and I'm trying to call gSearch.printMove(), however I'm getting the error
NullReferenceException: Object reference not set to an instance of an object
This is my Enemy script
public class Enemy1 : EnemyBrain {
public override void Start() {
base.Start ();
}
void FixedUpdate() {
moveNPC();
}
}
The error shows that it comes from EnemyBrain at gSearch.printMove();.
My code does a little bit more, but I think this simple example should be able show where my errors are coming from.
Any help is very much appreciated.
Thank you
Just to make sure... GreedySearch and Enemy1 scripts are on the same GameObject?
Try not overriding your start method. If you're just calling the base, there's no reason to override it.
But the problem is that probably there's no such component in the same gameObject. Are you sure your GreedySearch is at the same GameObject as the EnemyBrain script?
Hello Nose$$anonymous$$ills and nicolasjr, thanks for the reply. I am sure that I have all 3 scripts on my object, which is why this error looks very weird to me.
Well, do a verification, so that the method will only be called if the pointer is not null. That's good practice, anyways. Perhaps in the first frame your method is being called before starting the instance, hence the error.
Answer by SUMFX · Apr 22, 2015 at 03:45 PM
You are calling same object from itself:
public class GreedySearch : MonoBehaviour {
public GreedySearch gSearch;
If this is just a typo then two components EnemyBrain and GreedySearch must be on same gameobject since you are trying to get GreedySearch component without declaring parent:
public virtual void Start () {
gSearch = GetComponent<GreedySearch> ();
}
based on the whole post text, It seems to be a typo. He even says it's the EnemyBrain class.
Furthermore, the code wouldn't run, since there would exist two GreedySearch classes.
Your answer
Follow this Question
Related Questions
NullReferenceException help 1 Answer
[Closed]NullReferenceException on Object Instantiation onto game world 2 Answers
NullReferenceException: Object reference not set to an instance of an object 1 Answer
Pause menu error NullReferenceException:Object reference not set to an instance of an Object .js 1 Answer