I’m not sure if something better can be done instead of calling the OnCollisionEnter2D function, but it also keeps giving me the error: Assets\Scripts\BouneEnemyDestroy.cs(34,48): error CS1003: Syntax error, ‘,’ expected
Here is the code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BouneEnemyDestroy : MonoBehaviour
{
private float _delay = 10;
// Enemy Destroy On Collision
void OnCollisionEnter2D(Collision2D collision)
{
if(collision.gameObject.tag == "Player")
{
Destroy(gameObject);
}
if(collision.gameObject.tag == "Enemy")
{
Destroy(gameObject);
}
}
public void FixedUpdate()
{
if (_delay > 0)
{
_delay -= Time.fixedDeltaTime;
if (_delay <= 0)
{
OnCollisionEnter2D(Collision2D collision);
}
}
}
}
That’s not quite how you call methods. You need a Collision2D instance to pass into the method. In any case, you really shouldn’t be calling Unity’s magic methods yourself.
It looks like you want to destroy the game object? Why not just call Destroy when the delay has finished?
I would like it to destroy after the specified time but only if it interacts with another object through the collision, but I’m not sure if that’s a viable thing to do here
In that case you’d only want to start the counting down after something has interacted with it. Right now your logic is backwards.
You can take advantage of the fact that methods like Update or FixedUpdate don’t get called when a behaviour component is disabled (the check box in the inspector). So you can simply start with this.enabled set to false, and then flip it to true when something collides with the game object.
Something like this:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BouneEnemyDestroy : MonoBehaviour
{
private float _delay = 10;
private void Awake()
{
this.enabled = false;
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == "Player")
{
this.enabled = true;
}
if (collision.gameObject.tag == "Enemy")
{
this.enabled = true;
}
}
private void Update()
{
if (_delay > 0)
{
_delay -= Time.deltaTime;
if (_delay <= 0)
{
Destroy(this.gameObject);
}
}
}
}
Side note I changed FixedUpdate to Update as the former should only be used for physics related matters.
1 Like
Thank you very much for the help, I had thought of that being a possibility but didn’t know how to go about fixing it
1 Like