Search Unity

Resolved Unity cant assign references to GameObjects after insatiating them and their clones

Discussion in 'Scripting' started by stakensj, Dec 20, 2021.

  1. stakensj

    stakensj

    Joined:
    Oct 23, 2020
    Posts:
    35
    Basically, I am making a game where you run over chicken with a car, I have everything done, EXCEPT, the spawning script. After spawning around 20 clones unity just cant keep up with them, and causes the unity to create an error, and pause the game. Can someone explain why is it happening?
    To spawn chickens I use this script:

    Code (CSharp):
    1. using UnityEngine;
    2.     using System.Collections;
    3.  
    4.     public class Spawener_Chicken : MonoBehaviour
    5.     {
    6.         public GameObject Chicken;
    7.         public int xPos;
    8.         public int zPos;
    9.         public int enemyCount;
    10.         public int enemyLimit = 100;
    11.  
    12.      
    13.         void Start()
    14.         {
    15.             StartCoroutine(EnemySpawn());
    16.         }
    17.         void Update()
    18.         {
    19.          
    20.         }
    21.         IEnumerator EnemySpawn()
    22.         {
    23.             while (enemyCount < enemyLimit)
    24.             {
    25.                 xPos = Random.Range(-30, 30);
    26.                 zPos = Random.Range(-22, 22);
    27.                 Instantiate(Chicken, new Vector3(xPos, 1, zPos), Quaternion.identity);
    28.                 yield return new WaitForSeconds(0.1f);
    29.                 enemyCount += 1;  
    30.             }
    31.             while (enemyCount >= enemyLimit)
    32.             {
    33.                 StartCoroutine(EnemySpawn());
    34.             }
    35.         }
    36.  
    37.     }
    After spawning some, Unity starts giving out errors and pausing the game.
    This Is the error:

    NullReferenceException: Object reference not set to an instance of an object
    chicken.OnTriggerEnter (UnityEngine.Collider hit) (at Assets/scripts/chicken.cs:60)

    And This is the Chicken code:


    Code (CSharp):
    1. using System.Collections;
    2.     using System.Collections.Generic;
    3.     using UnityEngine;
    4.     using UnityEngine.AI;
    5.  
    6.     public class chicken : MonoBehaviour
    7.     {
    8.        private NavMeshAgent NMA;
    9.         public int testint1 = 99;
    10.         public int testint2;
    11.        private GameObject Visuals;
    12.        private GameObject ParticleSys;
    13.         public GameObject NumberBoy;
    14.         public Spawener_Chicken SpawnerCode;
    15.         void Start()
    16.         {
    17.             StartCoroutine(wait());
    18.         }
    19.  
    20.         void RealStart()
    21.         {
    22.             NumberBoy = GameObject.Find("/Car/Spawner for enemys");
    23.             SpawnerCode = NumberBoy.GetComponent<Spawener_Chicken>();
    24.             InvokeRepeating("ChangeDestination", 0, 5);
    25.             NMA = GetComponent<NavMeshAgent>();
    26.             Visuals = this.gameObject.transform.GetChild(0).gameObject;
    27.             ParticleSys = this.gameObject.transform.GetChild(1).gameObject;
    28.         }
    29.  
    30.         IEnumerator wait()
    31.         {
    32.             yield return new WaitForSeconds(1);
    33.  
    34.             RealStart();
    35.         }
    36.  
    37.         public Vector3 RandomNavmeshLocation(float radius)
    38.         {
    39.             Vector3 randomDirection = Random.insideUnitSphere * radius;
    40.             randomDirection += transform.position;
    41.             NavMeshHit hit;
    42.             Vector3 finalPosition = Vector3.zero;
    43.             if (NavMesh.SamplePosition(randomDirection, out hit, radius, 99999999))
    44.             {
    45.                 finalPosition = hit.position;
    46.             }
    47.             return finalPosition;
    48.         }
    49.         void ChangeDestination()
    50.         {
    51.            // Debug.Log("Changed destination");
    52.             NMA.SetDestination(RandomNavmeshLocation(testint1));
    53.         }
    54.  
    55.         private void OnTriggerEnter(Collider hit)
    56.         {
    57.             if (hit.gameObject.tag == "Car")
    58.             {
    59.                 testint1 = 0;
    60.                 Visuals.SetActive(false);
    61.                 ParticleSys.SetActive(true);
    62.                SpawnerCode.enemyCount--;
    63.                 //  Debug.Log(gameObject.name + ": THat GUY JUST HIT ME!");
    64.                 Destroy(gameObject, 2);
    65.             }
    66.  
    67.             if (hit.gameObject.tag == "Destroying Wall")
    68.             {
    69.                 SpawnerCode.enemyCount--;
    70.                 Destroy(gameObject, 0);
    71.             }
    72.  
    73.         }
    74.    
    75.     }
     
  2. stakensj

    stakensj

    Joined:
    Oct 23, 2020
    Posts:
    35
    Update: So I did a little brainstorming and realized it may be caused by the pause I do at the beginning of the chicken script in order for it not to require a NavMesh Agent right as it spawns in the air (where is no navmesh) So because of that I moved all the assigning scripts BEFORE the wait Coroutine and now it seemed to work at first but instead it just straight up freezes unity
    The New Code:
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.AI;
    5.  
    6. public class chicken : MonoBehaviour
    7. {
    8.    private NavMeshAgent NMA;
    9.     public int testint1 = 99;
    10.     public int testint2;
    11.    private GameObject Visuals;
    12.    private GameObject ParticleSys;
    13.     public GameObject NumberBoy;
    14.     public Spawener_Chicken SpawnerCode;
    15.     void Start()
    16.     {
    17.         NumberBoy = GameObject.Find("/Car/Spawner for enemys");
    18.         SpawnerCode = NumberBoy.GetComponent<Spawener_Chicken>();
    19.         NMA = GetComponent<NavMeshAgent>();
    20.         Visuals = this.gameObject.transform.GetChild(0).gameObject;
    21.         ParticleSys = this.gameObject.transform.GetChild(1).gameObject;
    22.         StartCoroutine(wait());
    23.     }
    24.  
    25.     void RealStart()
    26.     {
    27.  
    28.         InvokeRepeating("ChangeDestination", 0, 5);
    29.  
    30.     }
    31.  
    32.     IEnumerator wait()
    33.     {
    34.         yield return new WaitForSeconds(1);
    35.  
    36.         RealStart();
    37.     }
    38.  
    39.     public Vector3 RandomNavmeshLocation(float radius)
    40.     {
    41.         Vector3 randomDirection = Random.insideUnitSphere * radius;
    42.         randomDirection += transform.position;
    43.         NavMeshHit hit;
    44.         Vector3 finalPosition = Vector3.zero;
    45.         if (NavMesh.SamplePosition(randomDirection, out hit, radius, 99999999))
    46.         {
    47.             finalPosition = hit.position;
    48.         }
    49.         return finalPosition;
    50.     }
    51.     void ChangeDestination()
    52.     {
    53.        // Debug.Log("Changed destination");
    54.         NMA.SetDestination(RandomNavmeshLocation(testint1));
    55.     }
    56.  
    57.     private void OnTriggerEnter(Collider hit)
    58.     {
    59.         if (hit.gameObject.tag == "Car")
    60.         {
    61.             testint1 = 0;
    62.             Visuals.SetActive(false);
    63.             ParticleSys.SetActive(true);
    64.            SpawnerCode.enemyCount--;
    65.             //  Debug.Log(gameObject.name + ": THat GUY JUST HIT ME!");
    66.             Destroy(gameObject, 2);
    67.         }
    68.  
    69.         if (hit.gameObject.tag == "Destroying Wall")
    70.         {
    71.             SpawnerCode.enemyCount--;
    72.             Destroy(gameObject, 0);
    73.         }
    74.  
    75.     }
    76.  
    77. }
    78.  
     
  3. RadRedPanda

    RadRedPanda

    Joined:
    May 9, 2018
    Posts:
    1,647
    Well, the original error suggested that this line
    Visuals.SetActive(false);
    that something was null (unless that wasn't line 60 when you ran it). I'm guessing somewhere Visuals is set to null, and from looking in your Start method as the only reference to setting it, that OnTriggerEnter is being called before your Start method, I'm guessing from creating two chickens inside of each other. To fix this, I would move your stuff from Start to Awake instead, as that should (I believe) run before OnTriggerEnter.
     
  4. stakensj

    stakensj

    Joined:
    Oct 23, 2020
    Posts:
    35
    I probably found the problem. You see, I was looking through stuff whats happening in the game before the crash, and realized that when enemyCount reaches enemyLimit, the code I made that I thought will keep Enumerator awake in order for it to spawn chickens after the max limit was reached, but then one got destroyed so it needs to fill the blank space, was just a closed loop that caused unity to overload and in the result: crash it so I fixed it :)
     
  5. stakensj

    stakensj

    Joined:
    Oct 23, 2020
    Posts:
    35
    Can you show me like an example of how it should look?
     
  6. RadRedPanda

    RadRedPanda

    Joined:
    May 9, 2018
    Posts:
    1,647
    Change Start() to Awake()
     
  7. stakensj

    stakensj

    Joined:
    Oct 23, 2020
    Posts:
    35
    Ooooh, thank you! I finally understood what was causing the problem, I forgot to also bring Assigning of Visuals and Particle systems into the Start function instead of RealStart function, I also tried changing Start to Awake, but it didn't change anything. And at this point, I can finally close this thread. Thank you!
    Best regards, stakensj