[英]Unity 5. Raycast compare tag
我正在使用光線投射系統來檢測世界上的物品,如果光線投射檢測到一個蘋果並且我按“ E”,我的角色應該撿起那個特定的蘋果。 其他任何可拾取的對象也是如此。
除了用“ IF”語句對每個項目進行硬編碼以檢查該特定項目是否為目標外,我無法弄清楚如何做到這一點。
我對比較標簽有個想法,但是我看不到如何不必對所有內容進行硬編碼。
void Fire()
{
if (Physics.Raycast(transform.position, transform.forward, out hit, rayRange))
{
// If (Raycast hit enemy) Damage Enemy Accordingly based on weapon damage.
// If (Raycast hit Apple) Pick up apple.
// If (Raycast hit Drink) Pick up drink.
Destroy(hit.transform.gameObject); // Debug Only
Debug.Log(hit.transform.name); // Debug Only
}
nextFire = Time.time + fireRate; // Don't mind this.
}
我認為您正在尋找的功能是:GameObject.SendMessage
if (Physics.Raycast(transform.position, transform.forward, out hit, rayRange))
{
hit.collider.SendMessage("CheckHit");
// Destroy(hit.transform.gameObject); // Debug Only
// Debug.Log(hit.transform.name); // Debug Only
}
然后在您的“敵人”,“蘋果”或“飲料”腳本中放置一個名為“ CheckHit”的函數
即
public class AppleController : MonoBehaviour
{
public void CheckHit();
}
如果要將變量添加到“ CheckHit()”,請調用
hit.collider.SendMessage("CheckHit", 1.0f);
public class AppleController : MonoBehaviour
{
public void CheckHit(float something);
}
https://docs.unity3d.com/ScriptReference/GameObject.SendMessage.html
如果您想在hit.transform類中調用一個函數,則我的上一個答案有效。
我想,如果您想從當前Class內調用函數,則以下方法會更好。
如果您想從fire()函數中調用一個函數,則可以始終按照以下說明進行操作:
只是命名您的功能,例如
public void HandleApple();
public void HandleEnemy();
使用“ hit”標簽獲取帶有名稱的函數
有幾種方法可以通過上述鏈接中所述的名稱來調用函數,但是我認為通過使用“ hit.transform.tag”,您所要做的就是命名與其標簽相關的函數
if (Physics.Raycast(transform.position, transform.forward, out hit, rayRange))
string functionName = "Handle" + hit.transform.tag; // tag is "Apple"
然后通過通過“ functionName”(“ HandleApple”)調用函數來調用函數
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.