- Home /
How to ignore some events occurrence
Hi, Let's Imagine player shoots gameObjects with different tags. Let that be "Square", "Hex", and "Rectangle". When player shoots gameObject with tag "Square" and hits another gameObject with the same tag "Square", from previous shoots, I want to destroy previous gameObject and have the one which has been recently shot remain. Problem is when gameObject hits the another gameObject with the same tag, an event is fired twice and this makes both gameObjects disappear. Code I am using allows only one occurrence, so one GameObject will in fact get destroyed, but when player hits more than one GameObject with the same tag "Square", those will remain, and I want them to be destroyed as well, so in the end only remains the one that was shot lastly, and all gameObjects with the same tag "Square" that were hit in that particular shot get destroyed. Do you have any suggestions how can I do this?
private void OnCollisionEnter2D(Collision2D collision)
{
if (ignoreCollision) return;
Invoke("Landed", 1f); // creates new gameObject for the player to shoot
Debug.Log(gameObject.tag + " collided with " + collision.gameObject.tag);
ignoreCollision = true;
if (collision.gameObject.tag == gameObject.tag)
{
Destroy(collision.gameObject);
}
}
Answer by Dommnk · Apr 19 at 06:07 PM
Okay I managed to solve this issue myself using simple public bool isDestructible. Writing it down if anyone stumbles into same problem. So by default prefabs are not destructible - isDestructible equals to false. At the end of the script I change this property to true. So for next move it will be destroyable, however the one thats being shot is not. Works like a charm.
Answer by ogulcan_topsakal · Apr 18 at 10:55 PM
@Dommnk You can use the OnTriggerEnter2D event inside the objects you target instead of the gameobject you fired. When comparing tags, I recommend you to use them as in the example I gave Simple explanation.
target square, hex, triangle etc.
private void OnCollisionEnter2D(Collision2D col)
{
if (col.gameObject.CompareTag(gameObject.tag))
{
Destroy(gameObject);
}
}
@$$anonymous$$ Thank you for response. This condition however makes both objects getting destroyed - both gameObject and col.gameObject, and this breaks my code - not executing Landed method. Invoke("Landed");
gets canceled.
@Dommnk Remove destroy part on fired objects move that part to targets as given an example. If fired and target is same prefab I would separate that prefabs.
@$$anonymous$$ Sorry I don't understand what you mean "move to targets" as I handle every event in one class - BoxScipt. Exactly it is that fired object and target are the same prefabs, do you think that creating two sets of prefabs - one for the player to shoot and one for those existing ones in game would solve issue?