Hello! Here’s what I’m doing:
First the player clicks or presses “e” and a “rocket” is fired, it is a physics object with a circle collider 2d that is set as a trigger. When this hits the tile map it instantiates a “explosion.”
This explosion has a circle collider 2d which is NOT set as a trigger. The explosion has this script attached to it:
using System.Collections;
using System.Collections.Generic;
using System.Numerics;
using UnityEngine;
using UnityEngine.Tilemaps;
public class DestroyTilesOnCollision : MonoBehaviour
{
//public Tilemap tilemap;
public ContactPoint2D[] contacts = new ContactPoint2D[10];
public GameObject particles;
public AudioSource explodeAndHitNoise;
void OnCollisionStay2D(Collision2D collision)
{
Debug.Log("Hit!");
if (collision.gameObject.name == "Tilemap")
{
Debug.Log("Hit tilemap!");
int contactCount = collision.contactCount;
if (contactCount > contacts.Length)
contacts = new ContactPoint2D[contactCount];
collision.GetContacts(contacts);
UnityEngine.Vector3 hitPosition = UnityEngine.Vector3.zero;
for (int i = 0; i != contactCount; ++i)
{
hitPosition.x = contacts*.point.x;*
hitPosition.y = contacts*.point.y;*
collision.gameObject.GetComponent().SetTile(collision.gameObject.GetComponent().WorldToCell(hitPosition), null);
var newParticles = Instantiate(particles, hitPosition, UnityEngine.Quaternion.identity);
var newSoundEffect = Instantiate(explodeAndHitNoise, this.transform.position, this.transform.rotation);
StartCoroutine(DestroyParticles(newParticles));
}
}
}
public IEnumerator DestroyParticles(GameObject particles)
{
yield return new WaitForSeconds(3f);
Destroy(particles);
}
}
In the inspector this script is at the top, right below the transform component.
Below this script and the other components of the explosion is a script that destroys the circle collider 2d on the “explosion” after 0.03 seconds. So it has enough time to collide and destroy the tiles, but not so much that the player will be able to collide with it. Then I have another script that destroys the “explosion” after 3 seconds.
This works most of the time, but sometimes after the rocket is destroyed, Sometimes only the explosion spawns. Sometimes only the particles and sound effects spawn. And sometimes nothing spawns. Why is this? Thank you for any help, it is appreciated! Thank you again!