- Home /
Why does my "spawnedEnemies" variable not update when enemies are destroyed?
I'm creating a shooter game and I'm trying to update the current count of enemies on screen. When the laser hits an enemy, it is supposed to subtract 1 from the "spawnedEnemies" and then destroy the laser. What's happening is that the spawnedEnemies count doesn't update in game, only when the game is over. Then when the game is over, it shows a negative number. When the game starts, there is 0 enemies spawned.
This is my EnemyController class. When the "Enemy" is hit with a laser, it updates the "spawnedEnemies" int in the GameManager class. But it doesn't update it in game, only when the game is over and it shows a negative number. Ex: I spawn 5 enemies, I shoot all 5 of them and it shows -6 in the Inspector.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyController : MonoBehaviour
{
public GameManager theGM;
// Start is called before the first frame update
void Start()
{
}
private void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "Laser")
{
theGM.spawnedEnemies = theGM.spawnedEnemies - 1;
Destroy(this.gameObject);
}
}
}
This is my GameManager class:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameManager : MonoBehaviour
{
public int maxEnemiesAllowed;
public int spawnedEnemies;
public float timeBetweenEnemies;
public float nextEnemySpawn;
public GameObject[] enemies;
// Start is called before the first frame update
void Start()
{
spawnedEnemies = 0;
}
// Update is called once per frame
void Update()
{
float spawnPosition = Random.Range(-2.25f, 2.25f);
if(spawnedEnemies <= maxEnemiesAllowed && Time.time >= nextEnemySpawn)
{
Instantiate(enemies[0], new Vector3(spawnPosition, 6f, 0f), Quaternion.identity);
spawnedEnemies++;
nextEnemySpawn = Time.time + timeBetweenEnemies;
}
}
}
Answer by Anaxis_Studio · Sep 16, 2019 at 02:25 AM
My guess would be it's due to how you are handling hit detection. You're kind of using a workaround if you don't raycast for hit detection. For example, if it's possible to shoot twice before the enemy dies then that would result in a negative end score.
You could try and debug it to confirm but I can't see any other reason this would be happening.
private void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "Laser")
{
Debug.Log("hit registered");
theGM.spawnedEnemies = theGM.spawnedEnemies - 1;
Destroy(this.gameObject);
}
}
Answer by sisse008 · Sep 16, 2019 at 01:55 PM
do you have this line:
theGM.spawnedEnemies = theGM.spawnedEnemies - 1;
any where else in your project? maybe in OnDestroy() or OnDisable()??