Unity C# OnCollision Script: Detecting and Displaying Collision Events
This script is attached to a game object and handles collision events.
The script includes a reference to a collisionPanel game object, which is used to display collision information.
In the Start() method, the script sets the rigidbody's 'isKinematic' property to true, making the object's movement static. It also sets the collider's 'isTrigger' property to true, making it a trigger collider.
The OnTriggerEnter() method is called when the object collides with another collider. If the other collider has a tag of 'cube', the method returns without doing anything. Otherwise, it sets the CollisionText.Instance.str_CollisionText property to a string containing the names of the two colliding objects. It then calls the CollisionText.Instance.UpdateCollisionText() method to update the collision information in the UI. Finally, it sets the collisionPanel game object to active, making it visible.
public class OnCollision : MonoBehaviour
{
public GameObject collisionPanel;//定义信息提示框
void Start()
{
Rigidbody rb = GetComponent<Rigidbody>();
// 将刚体的运动类型设置为静态
rb.isKinematic = true;
// 将碰撞器设置为触发器
Collider collider = GetComponent<Collider>();
collider.isTrigger = true;
}
///物体发生碰撞///
private void OnTriggerEnter(Collider other)
{
//Debug.Log(gameObject.transform.name +'与'+ collision.transform.name+'发生碰撞 ');
if (other.tag == 'cube')
{
return;
}
else
{
CollisionText.Instance.str_CollisionText = gameObject.transform.name + '与' + other.gameObject.name + '发生碰撞!';//将物体碰撞的信息导入碰撞信息文本
}
CollisionText.Instance.UpdateCollisionText();//将物体碰撞的信息导入碰撞信息文本UI
collisionPanel.SetActive(true);//信息提示框显示
}
}
原文地址: https://www.cveoy.top/t/topic/eaAW 著作权归作者所有。请勿转载和采集!