【发布时间】:2018-09-30 06:03:21
【问题描述】:
我想在 Unity 中与游戏对象进行交互。这些对象可能是钥匙、门、箱子……
假设桌子上有一把钥匙。当玩家靠近它时,它应该被着色器勾勒出来,并且会出现一个文本“拾取键”。
我为可交互的游戏对象创建了一个界面。
public interface IInteractable
{
string InteractabilityInfo { get; }
void ShowInteractability();
void Interact();
}
通过这样做,我可以将界面组件添加到我的Key 脚本中
public class Key : MonoBehaviour, IInteractable
{
public string InteractabilityInfo { get { return "some text here"; } }
public void ShowInteractability()
{
// Outline Shader maybe?
}
public void Interact()
{
// Do something with the key
}
}
当涉及到检查某些东西是否可交互的脚本时,我创建了一个脚本,该脚本创建了一个用于检查可交互对象的光线投射。 (我将此脚本附加到我的 FPS 相机)
public class InteractabilityCheck : MonoBehaviour
{
private const int RANGE = 3;
private void Update()
{
RaycastHit hit;
if (Physics.Raycast(transform.position, transform.forward, out hit, RANGE))
{
IInteractable interactable = hit.collider.GetComponent<IInteractable>();
if (interactable != null)
{
interactable.ShowInteractability();
if (Input.GetKeyDown(KeyCode.E))
{
interactable.Interact();
}
}
}
}
}
此脚本尝试获取接口组件并在它不为空时调用其中的方法。
这段代码运行良好,但我不喜欢 Raycast 每帧触发一个。还有其他实现交互性的方法吗?
【问题讨论】: