“Object reference not set to an instance of an object”

Updated on January 21, 2016 in [A] Unity Scripting
Share on Facebook0Tweet about this on TwitterShare on Google+0Share on Reddit0
5 on January 21, 2016

Hi everyone, I am learning how to use varibles and methods from one script into another and in this script I have something not working. The following first script is supposed to be attached to an enemy IA which should move towards the position of the player to attack him (2D top-view survival shooter).

using UnityEngine;
using System.Collections;

public class IAattack : MonoBehaviour {

Vector2 robotBegPos;
PlayerPos playerPosScript;

void Awake () {
robotBegPos = new Vector2 (transform.position.x, transform.position.y);
}

void Update () {
playerPosScript = GetComponent<PlayerPos>();
Vector2.MoveTowards (robotBegPos, playerPosScript.playerPos, 1);
Vector2 robotPos = new Vector2 (transform.position.x, transform.position.y);
robotBegPos = robotPos;
}
}

Now, PlayerPos is the following script, which is attached to the player in order to retrieve information on his position in the world (I know there is probably a much better, faster and easier way to get the player coordinates, but I made decided to do it this way).

using UnityEngine;
using System.Collections;

public class PlayerPos : MonoBehaviour {

public Vector2 playerPos;

void Update () {
playerPos = new Vector2 (transform.position.x,transform.position.y);
}
}

Basically, the error given is “Object reference not set to an instance of an object” referring to the UNDERLINED row in the first script. Am I not importing the script and variable correctly? What didn’t I understand?

Cheers!

  • Liked by
Reply
3 on January 21, 2016

Mmn, robotBegPos should be the robot (enemy IA) beginning position actually, which I wanted to store as variable just after the robot spawned. Shouldn’t it store those transforms when I call it in the awake function?

Helpful
on January 21, 2016

Well awake should come before start, so I think there is no problem with that.. will try changing tht tomorrow and see what happens but I’m guessing the problem is in the imported script. Thx anwys man!

Show more replies
  • Liked by
Reply
Cancel