Search Unity

how do I fix this one time bug.

Discussion in 'Getting Started' started by sahilsharma220202004, May 15, 2021.

  1. sahilsharma220202004

    sahilsharma220202004

    Joined:
    Nov 18, 2020
    Posts:
    33
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using Pathfinding;
    5.  
    6. public class Enemy : MonoBehaviour
    7. {
    8.     private AIDestinationSetter aiDestSetterScript;
    9.     private GameObject player;
    10.  
    11.     void Start()
    12.     {
    13.         //Sets AI destination of enemy on player
    14.         aiDestSetterScript = GetComponent<AIDestinationSetter>();
    15.         player = GameObject.Find("Player");
    16.         aiDestSetterScript.target = player.GetComponent<Transform>();
    17.     }
    18.  
    19.     // If there is no player destroy enemy
    20.     private void FixedUpdate()
    21.     {
    22.         if (player == null)
    23.         {
    24.             Destroy(gameObject);
    25.         }
    26.     }
    27.  
    28.     // Enemy destroys player and himself on collision with player
    29.     private void OnCollisionEnter2D(Collision2D collision)
    30.     {
    31.         if (collision.gameObject.CompareTag("Player"))
    32.         {
    33.             Destroy(collision.gameObject);
    34.             Destroy(gameObject);
    35.         }
    36.     }
    37. [LIST]
    38. [*]In this script the line 16 is giving error that object reference not set to an instance of an object if
    39. [*]while playing my player dies.
    40. [*]it gives only one error bcz of one enemy creted who doesnt have anywhere to go.
    41. [*]how to fix this??
    42. [/LIST]
     
  2. Deleted User

    Deleted User

    Guest

    Is your player object in the hierarchy named "Player" ? Though it looks like it's in start you might be running into situation that the player isn't even created yet. I believe one solution is make private GameObject player public, scene window, select object with the Enemy script and then drag the player object over to the variable referenced in the inspector. another method I've used is FindWithTag, have to set the tag on the player object to "Player"
     
  3. sahilsharma220202004

    sahilsharma220202004

    Joined:
    Nov 18, 2020
    Posts:
    33
    Actually the error is caused in line 16 bcz when the enemy is instantiated the target is set to player, but if enemy has been instantiated and player dies then the ai target field becomes null and gives null reference exception
    I need a fix for this