Hey guys. I’m having a problem with my Enemy AI moving towards my player. It keeps saying “Object reference is not set to an instance of the Object”. Think anyone can help me fix it? My code is this;
If the error is in the first one, do you have an in-game object tagged as “Player” (with the exact same spelling and character case)? If it’s in the second one, does the object the above script is attached to have a Rigidbody2D component?
Regardless of the error, both of those lines are not very efficient and should not be done in Update() (you’re looking that information up in every frame - and they won’t change from frame to frame)…
You really should look those things up in Start() or Awake() once and cache a reference to them. Then, use that cached reference in Update - it’ll be much more efficient.
Alright, so my problem was solved by the user @Mavina (Thank you very much!!!). Unfortunately, the answer was deleted, so I will put a copy of it into this comment! Thank you again @Mavina!! (Here’s the fully fixed script!)
I deleted my answer because I saw right after posting it that @jgodfrey had basically posted the same thing my I only corrected the script. but @jgodfrey is correct that you really should be initializing those variable in Start() or Awake() like so
private Vector3 player;
private Vector2 playerdirection;
private float xDif;
private float yDif;
private float speed;
private Rigidbody2D rigidbody = null;
void start ()
{
speed = 10;
// only get the player once instead of every frame
player = GameObject.FindWithTag("Player");
// only get the rigidbody once instead of every frame
rigidbody = GetComponent<Rigidbody2D>();
System.String error = "";
if (player == null)
{
error = "GameObject.FindWithTag(Player) == null, ";
}
if (rigidbody == null)
{
error += "GetComponent<Rigidbody2D>() == null";
}
// only log the error once instead of every frame
if (error != "")
{
Debug.Log(error);
}
}
void Update ()
{
if ((player != null) && (rigidbody != null))
{
Vector3 position = player.transform.position;
xDif = player.x - transform.position.x;
yDif = player.y - transform.position.y;
playerdirection = new Vector2 (xDif, yDif);
rigidbody.AddForce(playerdirection.normalized * speed);
}
}