Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

What's causing this error?

Discussion in 'Getting Started' started by MathewAlden, Nov 17, 2015.

  1. MathewAlden

    MathewAlden

    Joined:
    Nov 10, 2013
    Posts:
    12
    I wrote a simple script that on every tick, it checks what "platform" is directly below the script's parent. It then makes the parent match the rotation of the platform. My script works well enough, but it throws an exception on every tick. It says "NullReferenceException: Object reference not set to an instance of an object" and it points to line 20. I've attached my code. Would anyone be kind enough to tell me what's causing the null reference?


    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class testmove : MonoBehaviour
    5. {
    6.     void Start ()
    7.     {
    8.        
    9.     }
    10.  
    11.     void Update ()
    12.     {
    13.    
    14.     }
    15.  
    16.     void FixedUpdate()
    17.     {
    18.         RaycastHit ground = new RaycastHit();
    19.         Physics.Raycast (transform.position, transform.forward, out ground);
    20.         transform.rotation = ground.transform.rotation;
    21.     }
    22. }
    23.  
     
  2. tedthebug

    tedthebug

    Joined:
    May 6, 2015
    Posts:
    2,570
    Put a break point in & then hover the mouse over all the variables to see which one is returning null. That should then let you work out what is happening.
     
  3. jhocking

    jhocking

    Joined:
    Nov 21, 2009
    Posts:
    813
    Ordinarily you'd want to break the line down further to see which part is null, but in this case it's obvious that it must be "ground". That means the raycast isn't always hitting something; are these platforms over a bottomless pit that the player traverses? I'd probably solve this by just putting "if (ground != null)" right before the ground.transform line; that way the code will only attempt to use "ground" if an object exists.
     
  4. MathewAlden

    MathewAlden

    Joined:
    Nov 10, 2013
    Posts:
    12
    In my test level, the object is always above a floor... Unless it's up-side-down and I didn't realize it. I'll have to check that.
     
    Last edited: Nov 18, 2015