Search Unity

Enemy Spawning Script Issues

Discussion in 'Scripting' started by arcturus783, Jun 28, 2022.

  1. arcturus783

    arcturus783

    Joined:
    Nov 12, 2021
    Posts:
    55
    Hello Everyone!

    I'm working on a 3D game inspired by Space Invaders, and for the past week I've been having an issue with the enemy spawning function, controlled by a script attached to the EventSystem. I have used Debug.Log() statements, and from what I could gather, the issue is that after the first few enemies are killed the wave is somehow increasing exponentially. This triggers sudden increases in the enemiesToSpawn variable (values upwards of 600) and mass spawns enemies. I've attached the script below, the relevant areas are Start(), Update(), SpawnEnemy(), and enemiesToSpawnZero(). I would really appreciate any help, even if it's just a nudge in the right direction! Thank you in advance!

    Code (CSharp):
    1.  
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using UnityEngine;
    5. using UnityEngine.UI;
    6. using UnityEngine.EventSystems;
    7. using TMPro;
    8. public class EventScript : MonoBehaviour
    9. {
    10.     public Button pause;
    11.     public GameObject window;
    12.     public Button resume;
    13.     public Button backToHub;
    14.     public Button settings;
    15.     public TextMeshProUGUI score;
    16.     public TextMeshProUGUI waveText;
    17.     string scoreNumber;
    18.     public GameObject Enemy;
    19.     public Slider speedControl;
    20.     public GameObject rightBton;
    21.     public GameObject leftBton;
    22.     public Button Return;
    23.     public int enemiesToSpawn = 0;
    24.     public int wave = 0;
    25.     float RandomXValue;
    26.     public Camera deathCamera;
    27.     public Camera mainCamera;
    28.     public GameObject redHaze;
    29.     public GameObject healthText;
    30.     public int enemiesKilled = 0;
    31.     public float delayTime = 3.0f;
    32.     public int health = 3;
    33.     void Start()
    34.     {
    35.         score = score.GetComponent<TextMeshProUGUI>();
    36.         pause.onClick.AddListener(Pause);
    37.         resume.onClick.AddListener(Pause);
    38.         settings.onClick.AddListener(OpenSettings);
    39.         Return.onClick.AddListener(Resume);
    40.         window.SetActive(false);
    41.         deathCamera.gameObject.SetActive(false);
    42.         redHaze.SetActive(false);
    43.         Invoke("newWave", 3.0f);
    44.         enemiesToSpawnZero();
    45.     }
    46.     void Update()
    47.     {
    48.         rightBton.GetComponent<SpaceshipRight>().speed = speedControl.value;
    49.         leftBton.GetComponent<SpaceshipLeft>().speed = speedControl.value;
    50.         score.SetText("Score: " + enemiesKilled.ToString());
    51.         if (enemiesToSpawn == 0 && enemiesKilled > wave * 2 - 1)
    52.         {
    53.             Invoke("enemiesToSpawnZero", delayTime);
    54.         }
    55.         if (enemiesToSpawn != 0)
    56.         {
    57.             float randomEnemyTimer = Random.Range(2.0f, 6.0f);
    58.             Invoke("SpawnEnemy", randomEnemyTimer);
    59.             enemiesToSpawn--;
    60.         }
    61.         if(health == 0)
    62.         {
    63.             death();
    64.         }
    65.         Debug.Log("Enemies to spawn: " + enemiesToSpawn);
    66.         Debug.Log("Wave: " + wave);
    67.     }
    68.     public void Pause()
    69.     {
    70.         if (window.activeInHierarchy)
    71.         {
    72.             window.SetActive(false);
    73.             Time.timeScale = 1;
    74.         }
    75.         else
    76.         {
    77.             Resume();
    78.         }
    79.     }
    80.     public void Resume()
    81.     {
    82.         window.SetActive(true);
    83.         settings.gameObject.SetActive(true);
    84.         backToHub.gameObject.SetActive(true);
    85.         resume.gameObject.SetActive(true);
    86.         Return.gameObject.SetActive(false);
    87.         Time.timeScale = 0;
    88.     }
    89.     public void OpenSettings()
    90.     {
    91.         resume.gameObject.SetActive(false);
    92.         settings.gameObject.SetActive(false);
    93.         backToHub.gameObject.SetActive(false);
    94.         Return.gameObject.SetActive(true);
    95.     }
    96.     public void SpawnEnemy()
    97.     {
    98.         RandomXValue = Random.Range(-100.0f, 100.0f);
    99.         Enemy.SetActive(true);
    100.         Instantiate(Enemy, new Vector3(RandomXValue, Enemy.transform.position.y, 130), Quaternion.identity);
    101.         Enemy.SetActive(false);
    102.     }
    103.     public void death()
    104.     {
    105.         healthText.SetActive(false);
    106.         score.gameObject.SetActive(false);
    107.         mainCamera.gameObject.SetActive(false);
    108.         deathCamera.gameObject.SetActive(true);
    109.         redHaze.SetActive(true);
    110.         Time.timeScale = 0.3f;
    111.     }
    112.     public void newWave()
    113.     {
    114.         waveText.gameObject.SetActive(false);
    115.     }
    116.     public void enemiesToSpawnZero()
    117.     {
    118.         wave++;
    119.         delayTime += 1.2f;
    120.         waveText.gameObject.SetActive(true);
    121.         waveText.SetText("Wave " + wave.ToString());
    122.         Invoke("newWave", 3.0f);
    123.         enemiesToSpawn = wave * 2;
    124.     }
    125. }
    126.  
    127.  
     
    Last edited: Jun 30, 2022
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,742
    This is likely going to require you to run the code and instrument it to figure out what it is doing.

    What is often happening in these cases is one of the following:

    - the code you think is executing is not actually executing at all
    - the code is executing far EARLIER or LATER than you think
    - the code is executing far LESS OFTEN than you think
    - the code is executing far MORE OFTEN than you think
    - the code is executing on another GameObject than you think it is
    - you're getting an error or warning and you haven't noticed it in the console window

    To help gain more insight into your problem, I recommend liberally sprinkling Debug.Log() statements through your code to display information in realtime.

    Doing this should help you answer these types of questions:

    - is this code even running? which parts are running? how often does it run? what order does it run in?
    - what are the values of the variables involved? Are they initialized? Are the values reasonable?
    - are you meeting ALL the requirements to receive callbacks such as triggers / colliders (review the documentation)

    Knowing this information will help you reason about the behavior you are seeing.

    If your problem would benefit from in-scene or in-game visualization, Debug.DrawRay() or Debug.DrawLine() can help you visualize things like rays (used in raycasting) or distances.

    You can also call Debug.Break() to pause the Editor when certain interesting pieces of code run, and then study the scene manually, looking for all the parts, where they are, what scripts are on them, etc.

    You can also call GameObject.CreatePrimitive() to emplace debug-marker-ish objects in the scene at runtime.

    You could also just display various important quantities in UI Text elements to watch them change as you play the game.

    If you are running a mobile device you can also view the console output. Google for how on your particular mobile target, such as this answer or iOS: https://forum.unity.com/threads/how-to-capturing-device-logs-on-ios.529920/ or this answer for Android: https://forum.unity.com/threads/how-to-capturing-device-logs-on-android.528680/

    Another useful approach is to temporarily strip out everything besides what is necessary to prove your issue. This can simplify and isolate compounding effects of other items in your scene or prefab.

    Here's an example of putting in a laser-focused Debug.Log() and how that can save you a TON of time wallowing around speculating what might be going wrong:

    https://forum.unity.com/threads/coroutine-missing-hint-and-error.1103197/#post-7100494

    You must find a way to get the information you need in order to reason about what the problem is.
     
    arcturus783 likes this.
  3. SimonJ9

    SimonJ9

    Joined:
    Feb 5, 2018
    Posts:
    17
    Code (CSharp):
    1.  
    2. if (enemiesToSpawn == 0 && enemiesKilled > wave * 2 - 1)
    3. {
    4.     Invoke("enemiesToSpawnZero", delayTime);
    5. }
    The wave starts at 0, assuming no other scripts are changing it. Then "wave * 2 - 1" equals -1, which means after you invoked SpawnEnemy() twice, this condition is always true until enemiesToSpawnZero() executes and increases the wave. It is invoking enemiesToSpawnZero() every frame for a duration of delayTime. You can check that by adding some Debug.Log() in your enemiesToSpawnZero() function. I didn't test the script, but if that is the case, you can do some simple fix such as initializing wave to 1 instead of 0.
     
  4. arcturus783

    arcturus783

    Joined:
    Nov 12, 2021
    Posts:
    55
    Thank you for your response! I tried changing it to 1, both in the script and the Inspector, but that didn't make a difference. Besides, I used the Invoke() method in Start() which increased the wave to 1 immediately so that the screen would show Wave 1 in the beginning. I'll continue trying to debug it for now, although there probably is a simple issue with my math as you suggested. Thank you again for taking the time to respond!
     
  5. arcturus783

    arcturus783

    Joined:
    Nov 12, 2021
    Posts:
    55
    Thank you for your response! That's what I was actually doing before, and now as well - I can usually debug easily, but this issue has persisted for over a week and I figured posting in the Forum would get fresh eyes on my script. I'll definitely use the methods you suggested, the first step to solving a problem is realizing it's there and understanding what it is - I haven't quite gotten to that second part yet, but hopefully in time I will. Thank you again!
     
  6. arcturus783

    arcturus783

    Joined:
    Nov 12, 2021
    Posts:
    55
    Update: I tried calling a function in Start() method to reflect what SimonJ9 said, but I didn't see any change - I updated the script in the original post. Based on what I can tell so far from Debug.Log statements, the enemiesToSpawn variable starts off normal, but after the first two enemies are killed the variable increases exponentially. Does anyone know any better debug methods that can help me get past this issue faster?
     
  7. SimonJ9

    SimonJ9

    Joined:
    Feb 5, 2018
    Posts:
    17
    Code (CSharp):
    1. Invoke("enemiesToSpawnZero", delayTime);
    It looks like this line is causing the problem you described. Now the wave starts at 1. After you killed 2 enemies,
    enemiesKilled > wave * 2 - 1
    becomes true. Since you are using Invoke(), your enemiesToSpawnZero() will not execute until it waits for delayTime. During this period, Invoke() is called every frame since it is in the Update(). Can you try to call enemiesToSpawnZero() directly and see if that fixes the issue?
     
    arcturus783 likes this.
  8. arcturus783

    arcturus783

    Joined:
    Nov 12, 2021
    Posts:
    55
    Thanks for your reply! That might be the issue, as I don’t remember the problem occurring until I added that as buffer time between waves. Unfortunately, I won’t be able to work on Unity for a couple of days, but when I get back on Monday I’ll check and see if that fixes the issue. Thank you again!
     
  9. arcturus783

    arcturus783

    Joined:
    Nov 12, 2021
    Posts:
    55
    This fixed the issue, thank you!