我正在統一創建一個簡單的 3d 平臺游戲,我正在努力做到這一點,因此如果您在某個半徑內并且按下“f”鍵,敵人就會消失。我正在檢查以確保敵人足夠接近以進行攻擊的方法是觸發球體,當它被觸發并且您按下“f”時,敵人將被移除。我目前正在嘗試查看是什么與觸發器相撞,但我無法弄清楚。這是我當前的代碼
using UnityEngine;
public class PlayerCombat : MonoBehaviour
{
public GameObject Enemy1;
public GameObject Enemy2;
public GameObject Enemy3;
public GameObject Enemy4;
// Update is called once per frame
void OnTriggerEnter (Trigger triggerInfo)
{
if (triggerInfo.collider.tag == "Enemy" & Input.GetKey("f"))
{
if (triggerInfo.collider.name == Enemy)
{
Enemy1.SetActive(false);
}
}
}
}
uj5u.com熱心網友回復:
簽名是并且一直是,OnTriggerEnter(Collider)否則該訊息方法將不會被 Unity 識別并且根本不會被呼叫!
然后你已經有了Collider……你還需要什么?
public class PlayerCombat : MonoBehaviour
{
// There is no need to know the enemy references beforehand at all
// you will get all required references from the Collider parameter of OnTriggerEnter itself
// I personally would however expose these two settings to the Inspector to be more flexible
// this way you can adjust these two settings within Unity without having to touch your code
public string listenToTag = "Enemy";
public KeyCode listenToKey = KeyCode.F;
// The signature has to be this otherwise the message method is never invoked at all
private void OnTriggerEnter (Collider other)
{
// Rather use "CompareTag" instead of `==` since the latter will silently fail
// for typos and nonexistent tags while "CompareTag" shows an error which is good for your debugging
// And in general you want to use the logical "&&" instead of the bitwise operator "&" for bools
if (other.CompareTag(listenToTag) && Input.GetKey(listenToKey))
{
// simply set the object you collide with inactive
other.gameObject.SetActive(false);
}
}
}
最后只需確保您所有的敵人實體實際上都有標簽 Enemy
uj5u.com熱心網友回復:
首先,我很確定 OnTriggerEnter 將 Collider 作為其引數,不是嗎?https://docs.unity3d.com/ScriptReference/Collider.OnTriggerEnter.html
您可以像這樣獲取碰撞物件的名稱
//Upon collision with another GameObject,
private void OnTriggerEnter(Collider other)
{
Debug.Log($"collided with {other.gameObject.name}");
//you can check for specific components too
MyComponent myComponent = other.GetComponent<MyComponent>();
if (myComponent != null) {
// do something if it has that component on it!
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/360395.html
