Search Unity

The object of type "GameObject" has been destroyed but you are still trying to access it.

Discussion in 'Scripting' started by kancelarija12, Oct 5, 2019.

  1. kancelarija12

    kancelarija12

    Joined:
    Sep 17, 2019
    Posts:
    15
    What causes this problem?
    Im trying to make a coop multiplayer game against ai so it has 2 players which might cause the error but im a begginer so i dont really know.
    Here is my code if it helps:
    Code (CSharp):
    1. using UnityEngine;
    2. public class followplayer : MonoBehaviour
    3. {
    4.     public GameObject Player;
    5.     public GameObject Player2;
    6.     public GameObject enemy;
    7.     public float maxdist = 30;
    8.     public float movementSpeed = 10;
    9.     void Update()
    10.     {
    11.         float distP1 = Vector3.Distance(Player.transform.position, enemy.transform.position);
    12.         float distP2 = Vector3.Distance(Player2.transform.position, enemy.transform.position);
    13.         if(distP1 <= maxdist)
    14.         {
    15.             if(distP2 <= distP1)
    16.             {
    17.                 transform.LookAt(Player2.transform);
    18.                 transform.position += transform.forward * movementSpeed * Time.deltaTime;
    19.             }
    20.             if (distP1 <= distP2)
    21.             {
    22.                 transform.LookAt(Player.transform);
    23.                 transform.position += transform.forward * movementSpeed * Time.deltaTime;
    24.             }
    25.         }
    26.         if (distP2 <= maxdist)
    27.         {
    28.             if (distP2 <= distP1)
    29.             {
    30.                 transform.LookAt(Player2.transform);
    31.                 transform.position += transform.forward * movementSpeed * Time.deltaTime;
    32.             }
    33.             if (distP1 <= distP2)
    34.             {
    35.                 transform.LookAt(Player.transform);
    36.                 transform.position += transform.forward * movementSpeed * Time.deltaTime;
    37.             }
    38.         }
    39.     }
    40. }
     
  2. Boz0r

    Boz0r

    Joined:
    Feb 27, 2014
    Posts:
    419
    One your three gameobjects is being destroyed in another script and you don't check for null.
     
  3. kancelarija12

    kancelarija12

    Joined:
    Sep 17, 2019
    Posts:
    15
    what do you mean destroyed?
     
  4. MNNoxMortem

    MNNoxMortem

    Joined:
    Sep 11, 2016
    Posts:
    723
    GameObject.Destroy, or Object.Destroy has been called on it. Either explicitly or implicitly by destroying a parent GameObject or unloading the scene it's root GameObject is in.