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

NullReferenceExeption althougth I assinged it? ( A* , A Star)

Discussion in 'Navigation' started by kaysteinhoff2003, Jun 5, 2020.

  1. kaysteinhoff2003

    kaysteinhoff2003

    Joined:
    Mar 22, 2020
    Posts:
    19
    I have a little EnemyAI which I made with a*. Everything works fine exept that my enemy doesn't move towards the player. I don't know if the NullReferenceExeption is the problem but I get it as soon as my enemy detects the player and should move. Does somebody know a* well? Could someone please help me I have no idea anymore!

    Here's my code:
    Code (CSharp):
    1. void OnPathComplete(Path p)
    2. {
    3.     if(!p.error)
    4.     {
    5.         path = p;
    6.         currWaypoint = 0;
    7.     }
    8. }
    9.  
    10. void Update()
    11.  {
    12.         var heading = player.position - transform.position;
    13.         var distance = heading.magnitude;
    14.         var direction = heading / distance;
    15.        
    16.         Debug.DrawRay(transform.position, direction * VisionDistance, Color.blue);
    17.        
    18.         if(!IsDead)
    19.         {
    20.             RaycastHit hit;
    21.            
    22.             if(Physics.Raycast(transform.position, direction, out hit))
    23.             {
    24.                 if(hit.transform.tag == "Player")
    25.                 {
    26.                     seeker.StartPath(rb.position, player.position, OnPathComplete);
    27.                    
    28.                     if(currWaypoint >= path.vectorPath.Count && path != null)
    29.                     {
    30.                         reachedEnd = true;
    31.                     }else{
    32.                         reachedEnd = false;
    33.                        
    34.                         Vector3 AI_direction = ((Vector3)path.vectorPath[currWaypoint] - rb.position).normalized;
    35.                         Vector3 force = AI_direction * speed * Time.deltaTime;
    36.                    
    37.                         rb.AddForce(force);
    38.                    
    39.                         float dist = Vector3.Distance(rb.position, path.vectorPath[currWaypoint]);
    40.                    
    41.                         if(dist < nextWaypointDist)
    42.                         {
    43.                             currWaypoint++;
    44.                         }
    45.                     }
    46.                 }
    47.             }
    48.         }
    49. }