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.
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() 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);
}
}