Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Object reference not set to an instance of an object

Discussion in 'Scripting' started by toffeelew, Mar 29, 2015.

  1. toffeelew

    toffeelew

    Joined:
    Mar 29, 2015
    Posts:
    1
    Hi I'm quite new to coding and am trying to learn javascript, however I'm stuck on a particular issue:/

    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)
    Aidamage.Update () (at Assets/Scripts/Part 2 - Survival GUI/Aidamage.js:19)

    Basically my game is a survival game, and I'm trying to allow my character to damage my npc, here is my code:

    var health = 20;
    var newhealth;
    var damage = 5;
    var wait_time = 2;
    var lock = 0;
    var rayLength = 10;


    function Update()
    {
    var hit : RaycastHit;
    var fwd = transform.TransformDirection(Vector3.forward);

    if(Physics.Raycast(transform.position, fwd, hit, rayLength))
    {
    playerAnim = GameObject.Find("FPSArms_Axe@Idle").GetComponent(PlayerControl);

    if(hit.collider.gameObject.tag == "enemy" & Input.GetButtonDown("Fire1") & playerAnim.canSwing == true) {
    newhealth -= 5;
    }
    if(health == 0){
    Destroy(GameObject);
    }
    }
    }

    Would anybody be able to help?
     
  2. GroZZleR

    GroZZleR

    Joined:
    Feb 1, 2015
    Posts:
    3,201
    NullReferenceException errors mean that an object is being used that doesn't have a value (i.e. it's null).

    Are you sure GameObject.Find("FPSArms_Axe@Idle") returns a value object before you use GetComponent(PlayerControl) on it? Try this:

    Code (csharp):
    1.  
    2. playerAnim = GameObject.Find("FPSArms_Axe@Idle");
    3. Debug.Log("Is this value null: " + playerAnim);
    4.  
    And see what pops up in the console. If it's null, then you need to fix the name of your object.
     
  3. Maurice_B

    Maurice_B

    Joined:
    Jan 10, 2014
    Posts:
    14
    same issue, Its annoying as it doesnt say what is null.
     
  4. LeftyRighty

    LeftyRighty

    Joined:
    Nov 2, 2012
    Posts:
    5,148
    the error has a line number on it, something on that line is null. If you have laid out you code nicely it really shouldn't be more than a couple of options.