Home > OS >  How to destroy objects on trigger enter in unity c#
How to destroy objects on trigger enter in unity c#

Time:01-02

I have a player moving in the Z axis and i want to spawn 3 objects and leave space for the player to move through

i tried to spawn 4 obstacles in front of the player and spawn with the obstacles an obstacle destroyer randomly to destroy one of the 4 obstacles but my code doesn't seem to work

public class ObstacleGenerationScript : MonoBehaviour
{
    public float spawnDelay = 2f;
    private float timer = 0f;
    public float spawnDistance = 500f;
    public float spawnY = 0.75f;
    public float spawnX = 0f;
    public Transform transform;

    public GameObject player;
    public GameObject obstacle;
    public GameObject destroyer;

    public void Start()
    {
        transform = gameObject.GetComponent<Transform>();
    }

    public void Update()
    {
        transform.position = new Vector3(spawnX,spawnY,player.transform.position.z   spawnDistance);

        if (timer < spawnDelay)
        {
            timer  = Time.deltaTime;
        }
        else
        {
            timer = 0f;
            SpawnObstacle();
        }
    }
    public void SpawnObstacle()
    {
        Instantiate(obstacle, transform.position, new Quaternion(0,0,0,0));
        Instantiate(destroyer, new Vector3(Random.Range(-6,6),1,transform.position.z), new Quaternion(0, 0, 0, 0));
    }
}
public class ObstacleDestroyerScript : MonoBehaviour
{
    private void OnTriggerEnter(Collider other)
    {
        if(other.tag == "Obstacle")
        {
            Destroy(other);
        }
    }
}

CodePudding user response:

Please be more specific when saying that your code does not work. If the issue is that OnTriggerEnter is not working, here are a few things that could have gone wrong:

  1. Destroy(other) is targeting a Collider component, not the GameObject. Use Destroy(other.gameObject) to destroy the GameObject
  2. Check that both the obstacle and obstacle destroyer have colliders, and the obstacle destroyer's collider is a trigger.
  3. Check that either the obstacles or the obstacle destroyer have a Rigidbody component. If they do not, OnTriggerEnter will not be called because it will not be detected.
  4. If you are working in 2D, you need to use OnTriggerEnter2D.
  5. Rather than saying new Quaternion(0, 0, 0, 0) it is better to say Quaternion.identity, to make sure that does not cause any problems with the objects' rotations.
  • Related