Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by PERFKNIGHT · Sep 01, 2017 at 08:23 AM · transformnullreferenceexceptionarrayslists

Null Ref Exception on a script that should have a reference in it?

I'm trying to create a game AI where it uses a tier-based system (that uses an array of lists of transforms) to support a pathfinding algorithm. Thus far, I'm around 99% the logic for the pathfinding algorithm works, though I've yet to test it because I get an NRE error when I test my pathfinding target acquisition. The error seems to occur in line 185 of the code (where it says drawnPath.Add(target.transform); in the Patrol function) no matter what I do. The debugs never occur and I am extremely frustrated because as far as I'm concerned, I have everything else assigned, not to mention the fact that I have an if target == null statement right in the Patrol function! Can anyone help?

 using System;
 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 using UnityEngine.AI;
 
 public class AIHovercraft : MonoBehaviour {
 
     public float hoverHeight;
     public float hoverForce;
     private float hoverStandard;
     public float speed;
     private Rigidbody rb;
     private bool onGround;
     private bool falling;
 
     [SerializeField]
     private NavMeshAgent enemy;
     public HoverVehicle player;
     public GameObject[] hovercraft;
 
     private int tier;
     private float altitude;
     private WaitForSeconds altCheckDelay = new WaitForSeconds(0.06f);
     private bool canCheck;
 
     public enum State
     {
         EVADE,
         CHASE,
         PATROL
     }
 
     public State state;
     private bool alive;
 
     public GameManagement gManager;
 
     #region EVADE
 
     private int wIndex;
     private Vector3 eDirect;
     private int eModifier;
     private WaitForSeconds waitForDamage = new WaitForSeconds(2f);
     private bool hasTakenDamage;
 
     #endregion
 
     #region CHASE
 
     private GameObject target;
 
     #endregion
 
     #region PATROL
 
     List<Transform>[] allWaypoints;
     List<Transform> drawnPath = new List<Transform>();
     private int pWIndex;
     public float maxDistance;
     public float threatDistance;
     public float nearestDistance;
     private float nearestStaticDistance;
     private bool isMarked;
 
     #endregion
 
     private void Awake()
     {
         allWaypoints = new List<Transform>[gManager.tiers];
         int i = 0;
         foreach (List<Transform> tier in allWaypoints)
         {
             allWaypoints[i] = new List<Transform>();
             i++;
         }
         
     }
 
     private void Start()
     {
         rb = GetComponent<Rigidbody>();
         enemy = GetComponent<NavMeshAgent>();
 
         enemy.updatePosition = true;
         enemy.updateRotation = false;
         state = State.PATROL;
         alive = true;
         hasTakenDamage = false;
         canCheck = true;
         nearestStaticDistance = nearestDistance;
         
         //Start FSM
         StartCoroutine("FSM");
     }
 
     private void Update()
     {
         CheckTier();
     }
 
     int CheckTier()
     {
         int i = 1;
         foreach (int height in gManager.tierThresholds)
         {
             if (transform.localPosition.y > height)
             {
                 tier = i;
             }
             i++;
         }
         StartCoroutine("TierDelay");
         return tier;
     }
 
     IEnumerator FSM()
     {
         while (alive)
         {
             switch (state)
             {
                 case State.PATROL:
                     Patrol();
                     break;
                 case State.CHASE:
                     Chase();
                     break;
                 case State.EVADE:
                     Evade();
                     break;
             }
             yield return null;
         }
     }
 
     IEnumerator TierDelay()
     {
         yield return altCheckDelay;
     }
 
     void Patrol()
     {
         foreach (GameObject hc in hovercraft)
         {
             float targetDistance = Vector3.Distance(hc.transform.position, transform.position);
             float targetAngle = Vector3.Angle(transform.position, hc.transform.position);
             var direction = hc.transform.position - transform.position;
             if (targetDistance <= maxDistance && targetAngle <= 90 && targetDistance < threatDistance)
             {
                 Ray ray = new Ray(transform.position, direction);
                 RaycastHit hit;
                 if (Physics.Raycast(ray, out hit))
                 {
                     if (hit.collider.CompareTag("Hovercraft"))
                     {
                         threatDistance = targetDistance;
                         target = hc;
                         state = State.CHASE;
                         return;
                     }
                 }
             }
         }
 
         nearestDistance = nearestStaticDistance;
 
         if (target == null)
         {
             pWIndex = 0;
             foreach (Transform point in allWaypoints[0])
             {
                 float targetDistance = Vector3.Distance(point.transform.position, transform.position);
                 float targetAngle = Vector3.Angle(transform.position, point.transform.position);
                 var direction = point.transform.position - transform.position;
                 if (targetDistance <= maxDistance && targetAngle <= 90 && targetDistance < nearestDistance)
                 {
                     nearestDistance = targetDistance;
                     target = point.gameObject;
                 }
             }
             drawnPath.Add(target.transform);
             isMarked = false;
 
             DrawPath();
             
             foreach (Transform waypoint in drawnPath)
             {
                 Debug.Log(waypoint);
             }
         }
         
     }
 
     private void DrawPath()
     {
         for (int i = 0; i < 4; i++)
         {
             Vector3 originPosition = drawnPath[i].position;
             RaycastHit hit;
             while (!isMarked)
             {
                 eModifier = UnityEngine.Random.Range(-1, 2);
                 if (eModifier == -1)
                 {
                     Physics.Raycast(originPosition, -transform.right, out hit);
                     if (hit.collider.gameObject.layer == tier + 7)
                     {
                         target = hit.collider.gameObject;
                     }
                 }
                 else if (eModifier == 0)
                 {
                     Physics.Raycast(originPosition, transform.forward, out hit);
                     if (hit.collider.gameObject.layer == tier + 7)
                     {
                         target = hit.collider.gameObject;
                     }
                 }
                 else if (eModifier == -1)
                 {
                     Physics.Raycast(originPosition, transform.right, out hit);
                     if (hit.collider.gameObject.layer == tier + 7)
                     {
                         target = hit.collider.gameObject;
                     }
                 }
                 else if (eModifier == 2)
                 {
                     Physics.Raycast(originPosition, transform.forward, out hit);
                     if (hit.collider.gameObject.layer == tier + 7)
                     {
                         target = hit.collider.gameObject;
                     }
                 }
                 if (target != null)
                 {
                     isMarked = true;
                 }
             }
             drawnPath.Add(target.transform);
             isMarked = false;
         }
     }
 
     void Chase()
     {
         Debug.Log("Chasing " + target.name);
     }
 
     void Evade()
     {
 
     }
 
     public void AccountWaypoints(Transform[] waypoints)
     {
         foreach (Transform waypoint in waypoints)
         {
             allWaypoints[waypoint.gameObject.layer - 8].Add(waypoint);
         }
     }
 
     private void FixedUpdate()
     {
         Hover();
     }
 
     private void Hover()
     {
         RaycastHit hit;
         Ray ray = new Ray(transform.position, -transform.up);
         if (Physics.Raycast(ray, out hit, hoverHeight))
         {
             float proportionalHeight = (hoverHeight - hit.distance) / hoverHeight;
             Vector3 appliedHoverForce = transform.up * proportionalHeight * hoverForce;
             //ForceMode.Acceleration helps smooth out the hovering.
             rb.AddForce(appliedHoverForce, ForceMode.Acceleration);
             onGround = true;
             falling = false;
             
         }
 
         else if (!Physics.Raycast(ray, out hit, hoverHeight + 1f))
         {
             onGround = false;
             falling = true;
         }
     }
        
 }

 




Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

2 Replies

· Add your reply
  • Sort: 
avatar image
1

Answer by cgarossi · Sep 01, 2017 at 09:36 AM

 drawnPath.Add(target.transform)

You are adding the target.transform but you aren't checking it is still null.

You have a loop above this line that appears to assign target, but this is conditional. If the condition is not met, then target is STILL null and you are attempting to read it's transform.

Simply add:

 if (target !=null) drawnPath.Add(target.transform);

Or ensure that target is always assigned within your foreach loop.

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
0

Answer by Xepherys · Sep 01, 2017 at 04:48 PM

You are actually ONLY executing it if target is null, then trying to work on something to create target, but you don't check further if it's still null. In other words:

target == null, so run this if-statement. Then try to assign target if this other statement is also true. But regardless of the former, add it to drawnPath. That's not sound at all.

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

83 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Array of Lists null exception when adding to list. 2 Answers

Find Active gameobject with tag and store in a List/Array as a Transform? 3 Answers

Getting NullReferenceException when creating class instance using List 1 Answer

Undo/back system using a List/Array 2 Answers

Add GameObjects to a list using OnTriggerEnter 0 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges