一、激活销毁
void OnEnable()//每次激活脚本时调用 {print("OnEnable");}void OnDisable()//脚本取消激活状态调用 {print("OnDisable");}void OnDestroy()//被销毁时调用 {print("OnDestroy");}
二、鼠标事件
/// <summary>/// 代码添加到需要变颜色的物体上/// </summary>void OnMouseEnter()//鼠标进入游戏对象时 执行 {GetComponent<Renderer>().material.color = Color.red;}void OnMouseExit()//鼠标离开时 {GetComponent<Renderer>().material.color = Color.blue;}void OnMouseDown()//鼠标点击 {GetComponent<Renderer>().material.color = Color.yellow;}void OnMouseUp()//鼠标抬起 {GetComponent<Renderer>().material.color = Color.green;}void OnMouseDrag()//鼠标拖拽 {GetComponent<Renderer>().material.color = Color.black;}//void OnMouseOver()//持续停留在游戏对象上//{// GetComponent<Renderer>().material.color = Color.gray;//}//void OnMouseUpAsButton()//当鼠标在同一个GUIElement或Collider按下,在释放时调用//{// GetComponent<Renderer>().material.color = Color.yellow;//}
三、触发事件
触发信息检测(需要勾选Is Trigger)
(1)void OnTriggerEnter(Collider other) 当进入触发器
(2)void OnTriggerExit(Collider other) 当退出触发器
(3)void OnTriggerStay(Collider other) 当逗留触发器
例1:
void OnTriggerEnter(Collider other){Destroy(gameObject);//销毁物体本身Destroy(other.gameObject);//销毁被碰撞的物体}
例2:
void OnTriggerEnter(Collider other){//当进入触发器的时候,打开isKinematic使物体停止运动。重新定位物体的位置。再把isKinematic关闭,使物体自动下落transform.GetComponent<Rigidbody>().isKinematic = true;//打开isKinematictransform.position = new Vector3(0, 3, 0);transform.GetComponent<Rigidbody>().isKinematic = false;}
四、碰撞器
碰撞信息检测
(1)void OnCollisionEnter(Collision other) 当进入碰撞器
(2)void OnCollisionExit(Collision other)
(3)void OnCollisionStay(Collision other)
例1:
void OnCollisionEnter(Collision other){Destroy(gameObject);//销毁物体本身Destroy(other.gameObject);//销毁被碰撞的物体(CollisionInfo)}
例2:
void OnCollisionStay(Collision other){//当这两个游戏对象名字相同时if (string.Equals("Cube",other.gameObject.name)){print("产生火花。。");}}