I have a GameObject, a script is thrown on it, on which Instantiate is executed, which is declared in the ob variable.

 public class spawnPrefabs : MonoBehaviour { public GameObject[] item = new GameObject[5]; public GameObject ob; void Start () { StartCoroutine(Inst()); } IEnumerator Inst() { int addXPos = Random.Range(0,4); Vector3 spawnPos = gameObject.transform.position + new Vector3(addXPos, 0, 0); yield return new WaitForSeconds(1.5f); ob = Instantiate(item[Random.Range(0, 5)],spawnPos,Quaternion.identity); Repeat(); } void Repeat() { StartCoroutine(Inst()); } } 

There is also an invisible GameObject under the stage with Box Collider.

  public class triggerDetect : MonoBehaviour { void OnTriggerExit(Collider other) { Destroy(other.gameObject); } } 

I need to prefab element that entered the trigger, retired, so as not to litter the scene with identical objects.

UPD: I forgot to note that I have a 2D project. As decided: OnTriggerEnter => OnTriggerEnter2D (Collider2D other) . It all worked!

I am new to Unity and to C # as a whole, do not judge me.

  • what does not work? script hangs, destroy written. Is that write OnTriggerEnter - Valera Kvip
  • In general, I used OnTriggerEnter, it did not work, I tried it with OnTriggerExit. - Funtazoid
  • so what doesn't work then? - Valera Kvip
  • The object itself is not deleted, although it hangs Rigidbody - Funtaoid
  • OnTriggerExit with OnTriggerEnter and write a trite Debug.Log("я тут"); inside Debug.Log("я тут"); and check if it works. - Alexey Shimansky

1 answer 1

Perhaps, the object with the second script, the collider is not tick " IsTrigger ". Put this tick, then the script will start processing objects. If this checkbox is not checked, the unit considers the collision to be more complex, which must be handled in OnCollisionEnter / OnCollisionExit methods OnCollisionExit

Istrigger

Update

There is another option. For example, your prefab is an empty GameObject , inside of which there is another object with a collider. Then the object inside will be destroyed, but its parent will remain in the game world and will litter it.

only the object itself is destroyed, not its parent

  • Is Trigger Worth - Funtazoid
  • I made a scene with your scripts. They work. So you forgot some little thing. For example, the prefab of spawn objects does not have a rigidbody, or a collider. Catch the spawning object on a pause and inspect it. In general, OnTrigger will not be called up under any of the following conditions: none of the colliding objects of RigidBody, no colliders of one of the objects, none of the colliders have a check mark IsTrigger - Aleksandr Akimov