【发布时间】:2018-09-24 17:37:57
【问题描述】:
在 Unity 中,我有一个附加了触发器的游戏对象。这个触发器监听进入、退出和停留事件。
当事件被执行时,碰撞对象被检查特定的接口组件。如果此接口组件不为空/已附加,则代码应从接口组件调用方法。
目前我正在这样做
public class LightSource : MonoBehaviour
{
private void OnTriggerEnter(Collider col)
{
HandleLight(col, LightAffectableAction.Enter);
}
private void OnTriggerExit(Collider col)
{
HandleLight(col, LightAffectableAction.Exit);
}
private void OnTriggerStay(Collider col)
{
HandleLight(col, LightAffectableAction.Stay);
}
private void HandleLight(Collider col, LightAffectableAction action)
{
ILightAffectable lightAffectable = col.GetComponent<ILightAffectable>();
if (lightAffectable != null) // Is the component attached?
{
switch (action)
{
case LightAffectableAction.Enter:
lightAffectable.EnterLight();
break;
case LightAffectableAction.Exit:
lightAffectable.ExitLight();
break;
case LightAffectableAction.Stay:
lightAffectable.StayInLight();
break;
}
}
}
private enum LightAffectableAction
{
Enter,
Exit,
Stay
}
}
但我真的不喜欢使用开关和枚举。也许触发器中的一堆游戏对象会导致性能问题。
有些方法包含一个out 参数,我想创建这样的东西
public class LightSource : MonoBehaviour
{
private void OnTriggerEnter(Collider col)
{
if(col.TryGetComponent(ILightAffectable, out ILightAffectable comp)) // Pass in the component type
{
comp.EnterLight();
}
}
private void OnTriggerExit(Collider col)
{
if(col.TryGetComponent(ILightAffectable, out ILightAffectable comp))
{
comp.ExitLight();
}
}
private void OnTriggerStay(Collider col)
{
if(col.TryGetComponent(ILightAffectable, out ILightAffectable comp))
{
comp.StayInLight();
}
}
}
但我不知道如何创建适合上面示例代码的扩展方法,如 TryGetComponent。
我传入一个组件类型作为参数,获取组件作为输出参数。
如何创建这样的方法?
【问题讨论】: