📅  最后修改于: 2023-12-03 14:44:53.769000             🧑  作者: Mango
OnTriggerEnter2D is a function in Unity and C# that is triggered when a GameObject with a Collider2D component enters another GameObject's Collider2D. This function is commonly used in game development to detect collisions between game objects.
void OnTriggerEnter2D(Collider2D other)
void
- The return type of the function. It means that the function does not return any value.OnTriggerEnter2D
- The name of the function.Collider2D other
- A parameter of type Collider2D. It represents the Collider2D component of the other game object that collided with the game object that this script is attached to.public class PlayerController : MonoBehaviour
{
void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("Coin"))
{
// Add score or collect the coin
Destroy(other.gameObject);
}
if (other.CompareTag("Enemy"))
{
// The player dies or loses a life
GameOver();
}
}
void GameOver()
{
// Code for game over
}
}
In this example, the function OnTriggerEnter2D is used to detect collisions between the player and other game objects with Collider2D components. If the other game object has a tag of "Coin", the player collects it and the coin is destroyed. If the other game object has a tag of "Enemy", the game is over and the function GameOver is called.
OnTriggerEnter2D is a useful function in game development that detects collisions between game objects with Collider2D components. Developers can use it to add gameplay mechanics, such as collecting items and fighting enemies.