Hi, I’m new to Unity and I’m attending a Udemy course on creating a galaxy shooter 2D game with C#. The game is complete and bug free, except for a spiting behaviour. I want he enemy fire be destroyed after the object destruction of the enemy. But unfortunately the enemy dies and it happens often that its fire spawns in the void space at the same position it explodes.
Here’s the code in Update():
void Update()
{
CalculateMovement(); // It doesn't matter in my case
if (Time.time > _canFire)
{
_fireRate = Random.Range(3.0f, 7.0f);
_canFire = Time.time + _fireRate;
_enemyFire = Instantiate(_laserPrefab, transform.position, Quaternion.identity);
}
}
Here is the OnTriggerEnter2D excerpt:
private void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("Player"))
{
Player player = other.GetComponent<Player>();
if (player != null)
{
player.Damage();
}
// Here I tried Destroy(_enemyFire); but it did not solve the problem
_anim.SetTrigger("OnEnemyDeath");
_speed = 0;
Destroy(GetComponent<Collider2D>());
_audioSource.Play();
Destroy(this.gameObject, 2.8f);
}
if (other.CompareTag("Laser"))
{
Destroy(other.gameObject);
if (_gameManager.isCoOpMode == false)
{
if (_playerOne != null)
{
_playerOne.AddScore();
}
}
else
{
if (_playerOne != null)
{
_playerOne.AddScore();
}
if (_playerTwo != null)
{
_playerTwo.AddScore();
}
}
// Also here I put Destroy(_enemyFire); but it did not solve the problem
_anim.SetTrigger("OnEnemyDeath");
_speed = 0;
Destroy(GetComponent<Collider2D>());
_audioSource.Play();
Destroy(this.gameObject, 2.8f);
}
}
I think the problem is that the fire instantiates just before explosion and, after a random time, it appears. I cannot understand how to avoid that. Consider that I destroy the enemy object after 2.8 seconds because an animation of about 2.8 seconds is attached to it to render the explosion.
Thanks in advance for the help.