OnEnable:物体被启用时调用,物体默认为被启用状态,所有游戏一开始即会被调用
void OnEnable() {
print("script was enabled");
}
OnDisable:物体被禁用时调用,游戏结束时,物体会被禁用,该函数会被执行
void OnDisable() {
print("script was removed");
}
OnDestroy:物体被销毁时调用,游戏结束时,物体会被销毁,该函数会被执行
void OnDestroy() {
print("Script was destroyed");
}
OnTriggerEnter:当碰撞体(collider)进入触发器(trigger)时调用。
void OnTriggerEnter(Collider other) {
Destroy(other.gameObject);
}
OnTriggerStay:当碰撞体接触触发器时,每一帧被调用
void OnTriggerStay(Collider other) {
if (other.attachedRigidbody)
other.attachedRigidbody.AddForce(Vector3.up * 10);
}
OnTriggerExit:当碰撞体停止触发触发器时调用
void OnTriggerExit(Collider other) {
Destroy(other.gameObject);
}
OnCollisionEnter:当此Collider/Rigidbody触发另一个Collider/Rigidbody时调用
public class ExampleClass : MonoBehaviour {
AudioSource audio;
void Start() {
audio = GetComponent();
}
void OnCollisionEnter(Collision collision) {
foreach (ContactPoint contact in collision.contacts) {
Debug.DrawRay(contact.point, contact.normal, Color.white);
}
if (collision.relativeVelocity.magnitude > 2)
audio.Play();
}
}
OnCollisionStay:当此Collider/Rigidbody触发另一个Collider/Rigidbody时,每一帧被调用
void OnCollisionStay(Collision collisionInfo) {
foreach (ContactPoint contact in collisionInfo.contacts) {
Debug.DrawRay(contact.point, contact.normal, Color.white);
}
}
OnCollisionExit:当此Collider/Rigidbody停止触发另一个Collider/Rigidbody时调用
void OnCollisionExit(Collision collisionInfo) {
print("No longer in contact with " + collisionInfo.transform.name);
}
OnMouseEnter:当鼠标进入GUI元素或Collider时被触发,每次进入只会出发一次。
OnMouseOver:当鼠标悬浮在GUI元素或Collider时被触发,若没离开则每一帧被触发一次。
OnMouseExit:当鼠标离开GUI元素或Collider时被触发。
OnMouseDown:当鼠标在GUI元素或Collider上点击时触发。
OnMouseUp:当释放鼠标时调用。
OnMouseDrag:当鼠标拖拽GUI元素或Collider时触发
OnMouseUpAsButton:当鼠标在同一个GUI元素或Collider上点击并释放时触发。
void OnMouseDown()
{
Debug.Log("On Mouse Down");
}
void OnMouseEnter()
{
Debug.Log("On Mouse Enter");
}
void OnMouseExit()
{
Debug.Log("On Mouse Exit");
}
void OnMouseUp()
{
Debug.Log("On Mouse Up");
}
void OnMouseDrag()
{
Debug.Log("On Mouse Drag");
}
void OnMouseOver()
{
Debug.Log("On Mouse Over");
}
官方链接
https://docs.unity3d.com/ScriptReference/MonoBehaviour.html