Trigger

JunDev·2025년 3월 11일

Unity

목록 보기
5/8

OnTriggerEnter2D()

OnTriggerEnter2D() is a collision detection method that is called when a 2D Collider enters a Trigger Zone in Unity. This is commonly used in 2D physics-based games to detect when objects enter specific areas, like when a character enters a zone, picks up an item, or triggers an event.

  • OnTriggerEnter2D(Collider2D other) is a method that is automatically called when a 2D collider (like BoxCollider2D, CircleCollider2D, etc.) enters another 2D trigger collider.
  • A trigger collider is a special type of collider that does not physically interact with objects (i.e., it does not block or bounce objects). Instead, it is used purely for detection purposes.
void OnTriggerEnter2D(Collider2D other)
{
    // Code to execute when another collider enters the trigger
}
// Example
using UnityEngine;

public class PickupItem : MonoBehaviour
{
    void OnTriggerEnter2D(Collider2D other)
    {
        if (other.CompareTag("Player")) // Check if the object entering the trigger is the player
        {
            Debug.Log("Player picked up the item!");
            Destroy(gameObject); // Destroy the item when the player picks it up
        }
    }
}

OnBecameInvisible()

OnBecameInvisible() is a special Unity method that is automatically called when the GameObject's renderer is no longer visible by any active camera in the scene. It can be used to trigger actions when the object is out of view (e.g., stop animations, disable components, etc.).

void OnBecameInvisible()
{
    // Code to execute when the object is no longer visible to any camera
}
using UnityEngine;

public class ObjectVisibility : MonoBehaviour
{
    void OnBecameInvisible()
    {
        // Disable the GameObject when it is no longer visible to any camera
        gameObject.SetActive(false);
    }
}
profile
Jun's Dev Journey

0개의 댓글