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. Dismiss Notice

NullReferenceException

Discussion in 'Scripting' started by Ashuuu, Oct 24, 2016.

  1. Ashuuu

    Ashuuu

    Joined:
    Oct 24, 2016
    Posts:
    5
    Hello guys,I have zero knowledge of c# so please help accordingly.I can't fix the run time error NullReferenceException in this code.(WayPointProgressTracker.cs line 95(mentioned in the code comment))
    Please guide me.
    Code:

    Code (CSharp):
    1. using System;
    2. using UnityEngine;
    3.  
    4. namespace UnityStandardAssets.Utility
    5. {
    6.     public class WaypointProgressTracker : MonoBehaviour
    7.     {
    8.         // This script can be used with any object that is supposed to follow a
    9.         // route marked out by waypoints.
    10.  
    11.         // This script manages the amount to look ahead along the route,
    12.         // and keeps track of progress and laps.
    13.  
    14.         [SerializeField] private WaypointCircuit circuit; // A
    15. reference to the waypoint-based route we should follow
    16.  
    17.         [SerializeField] private float lookAheadForTargetOffset = 5;
    18.         // The offset ahead along the route that the we will aim for
    19.  
    20.         [SerializeField] private float lookAheadForTargetFactor = .1f;
    21.         // A multiplier adding distance ahead along the route to aim
    22. for, based on current speed
    23.  
    24.         [SerializeField] private float lookAheadForSpeedOffset = 10;
    25.         // The offset ahead only the route for speed adjustments
    26. (applied as the rotation of the waypoint target transform)
    27.  
    28.         [SerializeField] private float lookAheadForSpeedFactor = .2f;
    29.         // A multiplier adding distance ahead along the route for
    30. speed adjustments
    31.  
    32.         [SerializeField] private ProgressStyle progressStyle =
    33. ProgressStyle.SmoothAlongRoute;
    34.         // whether to update the position smoothly along the route
    35. (good for curved paths) or just when we reach each waypoint.
    36.  
    37.         [SerializeField] private float pointToPointThreshold = 4;
    38.         // proximity to waypoint which must be reached to switch
    39. target to next waypoint : only used in PointToPoint mode.
    40.  
    41.         public enum ProgressStyle
    42.         {
    43.             SmoothAlongRoute,
    44.             PointToPoint,
    45.         }
    46.  
    47.         // these are public, readable by other objects - i.e. for an
    48. AI to know where to head!
    49.         public WaypointCircuit.RoutePoint targetPoint { get; private set; }
    50.         public WaypointCircuit.RoutePoint speedPoint { get; private set; }
    51.         public WaypointCircuit.RoutePoint progressPoint { get; private set; }
    52.  
    53.         public Transform target;
    54.  
    55.         private float progressDistance; // The progress round the
    56. route, used in smooth mode.
    57.         private int progressNum; // the current waypoint number, used
    58. in point-to-point mode.
    59.         private Vector3 lastPosition; // Used to calculate current
    60. speed (since we may not have a rigidbody component)
    61.         private float speed; // current speed of this object
    62. (calculated from delta since last frame)
    63.  
    64.         // setup script properties
    65.         private void Start()
    66.         {
    67.             // we use a transform to represent the point to aim for,
    68. and the point which
    69.             // is considered for upcoming changes-of-speed. This
    70. allows this component
    71.             // to communicate this information to the AI without
    72. requiring further dependencies.
    73.  
    74.             // You can manually create a transform and assign it to
    75. this component *and* the AI,
    76.             // then this component will update it, and the AI can read it.
    77.             if (target == null)
    78.             {
    79.                 target = new GameObject(name + " Waypoint Target").transform;
    80.             }
    81.  
    82.             Reset();
    83.         }
    84.  
    85.  
    86.         // reset the object to sensible values
    87.         public void Reset()
    88.         {
    89.             progressDistance = 0;
    90.             progressNum = 0;
    91.             if (progressStyle == ProgressStyle.PointToPoint)
    92.             {
    93.                 target.position = circuit.Waypoints[progressNum].position;
    94.                 target.rotation = circuit.Waypoints[progressNum].rotation;
    95.             }
    96.         }
    97.  
    98.  
    99.         private void Update()
    100.         {
    101.             if (progressStyle == ProgressStyle.SmoothAlongRoute)
    102.             {
    103.                 // determine the position we should currently be aiming for
    104.                 // (this is different to the current progress
    105. position, it is a a certain amount ahead along the route)
    106.                 // we use lerp as a simple way of smoothing out the
    107. speed over time.
    108.                 if (Time.deltaTime > 0)
    109.                 {
    110.                     speed = Mathf.Lerp(speed, (lastPosition -
    111. transform.position).magnitude/Time.deltaTime,
    112.                                        Time.deltaTime);
    113.                 }//below is line 95
    114.                 target.position =
    115.                     circuit.GetRoutePoint(progressDistance +
    116. lookAheadForTargetOffset + lookAheadForTargetFactor*speed)
    117.                            .position;
    118.                 target.rotation =
    119.                     Quaternion.LookRotation(
    120.                         circuit.GetRoutePoint(progressDistance +
    121. lookAheadForSpeedOffset + lookAheadForSpeedFactor*speed)
    122.                                .direction);
    123.  
    124.  
    125.                 // get our current progress along the route
    126.                 progressPoint = circuit.GetRoutePoint(progressDistance);
    127.                 Vector3 progressDelta = progressPoint.position -
    128. transform.position;
    129.                 if (Vector3.Dot(progressDelta, progressPoint.direction) < 0)
    130.                 {
    131.                     progressDistance += progressDelta.magnitude*0.5f;
    132.                 }
    133.  
    134.                 lastPosition = transform.position;
    135.             }
    136.             else
    137.             {
    138.                 // point to point mode. Just increase the waypoint if
    139. we're close enough:
    140.  
    141.                Vector3 targetDelta = target.position - transform.position;
    142.                if (targetDelta.magnitude < pointToPointThreshold)
    143.                {
    144.                    progressNum = (progressNum + 1)%circuit.Waypoints.Length;
    145.                }
    146.  
    147.  
    148.                target.position = circuit.Waypoints[progressNum].position;
    149.                target.rotation = circuit.Waypoints[progressNum].rotation;
    150.  
    151.                // get our current progress along the route
    152.                progressPoint = circuit.GetRoutePoint(progressDistance);
    153.                Vector3 progressDelta = progressPoint.position -
    154. transform.position;
    155.                if (Vector3.Dot(progressDelta, progressPoint.direction) < 0)
    156.                {
    157.                    progressDistance += progressDelta.magnitude;
    158.                }
    159.                lastPosition = transform.position;
    160.            }
    161.        }
    162.  
    163.  
    164.        private void OnDrawGizmos()
    165.        {
    166.            if (Application.isPlaying)
    167.            {
    168.                Gizmos.color = Color.green;
    169.                Gizmos.DrawLine(transform.position, target.position);
    170.  
    171. Gizmos.DrawWireSphere(circuit.GetRoutePosition(progressDistance), 1);
    172.                Gizmos.color = Color.yellow;
    173.                Gizmos.DrawLine(target.position, target.position +
    174. target.forward);
    175.            }
    176.        }
    177.    }
    178. }
     
    Last edited: Oct 24, 2016
  2. DonLoquacious

    DonLoquacious

    Joined:
    Feb 24, 2013
    Posts:
    1,667
    The top of each forum here has a post called Use Code Tags Properly. You can use Insert -> Code in the toolbar to do this easily, but now that you've hit submit without them the code has lost all whitespace/tabs. You'll need to edit, delete all of the code, then re-copy from your IDE and re-paste into the Insert->Code window to get it to format properly.
     
    Ashuuu likes this.
  3. Ashuuu

    Ashuuu

    Joined:
    Oct 24, 2016
    Posts:
    5
    I'm sorry,I'm new to it.Thanks
     
  4. Ashuuu

    Ashuuu

    Joined:
    Oct 24, 2016
    Posts:
    5
    Done
     
  5. DonLoquacious

    DonLoquacious

    Joined:
    Feb 24, 2013
    Posts:
    1,667
    NullReferenceException means that a variable that's supposed to point to a class reference is set to null (no reference assigned to it), but is still trying to be accessed as if there's an object there. The following line:
    Code (csharp):
    1. target.position = circuit.GetRoutePoint(progressDistance + lookAheadForTargetOffset + lookAheadForTargetFactor * speed).position;
    ... must have a reference that is null but still being accessed. "progressDistance", "lookAheadForTargetOffset", "lookAheadForTargetFactor", and "speed" are all float values- "value types" and can't be null. That leaves "target" and "circuit", or possibly that GetRoutePoint on the circuit script is supposed to return a Transform object but is returning NULL instead.

    Target looks like if it isn't assigned in the inspector, it automatically gets a value in the Start function (a new object created and assigned to this reference), so unless it's explicitly made "null" somewhere in this code, or the object is destroyed, it shouldn't be throwing the exception. "circuit" on the other hand, has no such guarantee. My guess is that it absolutely has to be assigned in the inspector for things to function here, but it isn't assigned.

    Worth noting that when you get NullReferenceExceptions, you can narrow them down very quickly by using a Debug.Log or two and outputting whether or not references are null. For instance, if right before the line that gives the error, you write:
    Code (csharp):
    1. if(target == null)
    2.     Debug.Log("Target is NULL");
    3.  
    4. if(circuit == null)
    5.     Debug.Log("Circuit is NULL");
    ... then you can narrow this down really quick. Debug.Log is your friend, so like all friends you should use it often and never thank it for anything.
     
    Last edited: Oct 24, 2016
  6. Ashuuu

    Ashuuu

    Joined:
    Oct 24, 2016
    Posts:
    5
    I somewhat understood what you want to say.I added
    Code (CSharp):
    1. if(target==null)
    2. {
    3. target = new GameObject(name+ "WayPoint Target").transform;
    4. Debug.Log("Target is NULL");
    5. }
    6. if(circuit == null)
    7.  {
    8.  Debug.Log("Circuit is NULL");
    9. }
    and it showed Target is NULL and Circuit is NULL in the console.But I still don't know how to fix it
     
  7. DonLoquacious

    DonLoquacious

    Joined:
    Feb 24, 2013
    Posts:
    1,667
    The "circuit" definition at the top is as follows:
    Code (csharp):
    1. [SerializeField] private WaypointCircuit circuit;
    A public field in a MonoBehaviour script, or using SerializeField on a private field like this one, means that it's being shown in the inspector. If you click the object this script is attached to in the scene, you'll see a slot called "circuit" that accepts a WaypointCircuit type reference. You need to drag the WaypointCircuit object (some other object in your scene) into this slot so that it's referencing something.

    I highly recommend that you get onto the Learn section of the Unity website and watch the videos in the "Essentials" and "Scripting" portions of the Tutorials, at the bare minimum. It'll help you tremendously in figuring out the unique aspects of working with Unity. Also, you should pick up a book on C# if you don't have one yet. I recommend "The C# Player's Guide" by RB Whitaker if you're new to programming in general, or "C# Essentials" and/or "C# in a Nutshell" if you're familiar with other programming languages but just new to C#.
     
  8. Ashuuu

    Ashuuu

    Joined:
    Oct 24, 2016
    Posts:
    5
    Yeah I know it's hard to explain.I found the circuit slot in Waypoint progress tracker (script).Just help this last time.I added FPSController in it.Now in another script(Waypoint Circuit) it's asking for something in Transform slot and I can't insert anything in it
     
  9. DonLoquacious

    DonLoquacious

    Joined:
    Feb 24, 2013
    Posts:
    1,667
    I have no way of knowing what you're referring to, as I don't know anything about your Waypoint Circuit script or have any information on what kind of error it's giving.
     
  10. makeshiftwings

    makeshiftwings

    Joined:
    May 28, 2011
    Posts:
    3,350
    If a slot is asking for a Transform, you can drag any game object into the slot. All GameObjects have transforms. The part at the top of the inspector with the position and rotation etc is the Transform.