我正在使用光线投射系统来检测世界上的物品,如果光线投射检测到苹果,我按“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.
}
答案 0 :(得分:0)
我认为你正在寻找这个函数: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
}
然后在你的脚本中为#34;敌人"," Apple"或"喝"放一个名为" 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
答案 1 :(得分:0)
如果你想在hit.transform类中调用一个函数,我的上一个答案是有效的。
我想如果你想从当前的Class中调用一个函数,那么下面的方法会更好。
如果你想从fire()函数调用一个函数,你可以随时执行以下解释:
Calling a function from a string in C#
只需命名您的功能,例如
public void HandleApple();
public void HandleEnemy();
使用“命中”标记
获取使用名称调用的函数有几种方法可以通过上面链接中描述的名称来调用函数,但是我想通过使用“hit.transform.tag”你只需要命名与你的标签相关的函数
if (Physics.Raycast(transform.position, transform.forward, out hit, rayRange))
string functionName = "Handle" + hit.transform.tag; // tag is "Apple"
然后通过“functionName”(“HandleApple”)
调用该函数来调用该函数