Search Unity

NullException Error

Discussion in 'Scripting' started by GRiDxkl, Apr 20, 2014.

  1. GRiDxkl

    GRiDxkl

    Joined:
    Apr 20, 2014
    Posts:
    2
    Script:
    var target : Transform;
    var moveSpeed = 3;
    var rotationSpeed = 3;
    var myTransform : Transform;

    function Awake()
    {
    myTransform = transform;
    }

    function Start()
    {
    target = GameObject.FindWithTag("Player").transform;
    }

    function Update(){
    transform.LookAt(Vector3(target.position.x, transform.position.y, target.position.z));

    myTransform.Translate(Vector3.foward * moveSpeed * Time.deltaTime);
    }


    This is my error:
    NullReferenceException: Object reference not set to an instance of an object
    Boo.Lang.Runtime.RuntimeServices.InvokeBinaryOperator (System.String operatorName, System.Object lhs, System.Object rhs)
    AIFollow.Update () (at Assets/AIFollow.js:19)


    What am I failing to assign?
     
  2. frankrs

    frankrs

    Joined:
    Aug 29, 2009
    Posts:
    300
    maybe try

    transform.LookAt(target);
     
  3. BlueFragment27

    BlueFragment27

    Joined:
    Apr 16, 2014
    Posts:
    4
    Have you checked if your object has the tag "Player"?
    If yes, is it active/enabled?

    If no to any of the two questions, GameObject.FindWithTag("Player") will return null. Thus, you get the error when you use target in the Update() function.
     
  4. Dantus

    Dantus

    Joined:
    Oct 21, 2009
    Posts:
    5,667
  5. GRiDxkl

    GRiDxkl

    Joined:
    Apr 20, 2014
    Posts:
    2
    I closed Unity and opened back up and the error was gone...Strange. Thank everyone for their suggestions. Now I know what to look for if problem arises in future.