英文:
Is there a good way to manage OnTrigger() functions in Unity?
问题
在Unity中,这个函数通常需要附加到多个对象上,必须为对象编写脚本,而代码只有细微的更改。有没有一种好的方法可以像一次性集成所有内容一样管理它?
或者最好是为每个对象的OnTrigger()创建一个脚本并将其作为组件放置?
如果您有自己的好方法,我将不胜感激。
我尝试过将函数单独管理,但似乎必须将其附加为对象的组件。
英文:
In Unity, this function often has to be attached to multiple objects, must be scripted to the object, and there are only minor changes in the code. Is there a good way to manage this like integrating it all at once?
Or is it best to make a script for OnTrigger() on every object and put it as a component?
I would appreciate it if you could let me know if you have your own good method.
I tried to manage the function separately, but it seems like it must be attached as a component to the object.
答案1
得分: 1
我通常会创建一个名为CollisionEvents
的组件,其中包含不同触发选项的UnityEvent
属性。然后,当我想要连接到游戏对象的OnTrigger
函数时,只需包含这个组件,并在检查器中放置我想要调用的函数。
public class CollisionEvents : MonoBehaviour {
[field: SerializeField]
public UnityEvent TriggerEnterEvent { get; private set; }
[field: SerializeField]
public UnityEvent TriggerStayEvent { get; private set; }
[field: SerializeField]
public UnityEvent TriggerExitEvent { get; private set; }
public void OnTriggerEnter => TriggerEnterEvent?.Invoke();
public void OnTriggerStay => TriggerEnterEvent?.Invoke();
public void OnTriggerExit => TriggerEnterEvent?.Invoke();
}
这样做允许您像正常的Unity事件一样在检查器中访问这些函数,并且在代码中使用collisionEvents.TriggerEnterEvent.AddListener()
来访问它们,同时保持了属性的合理保护级别。
希望这有助于解答您的问题。
英文:
I usually make a component called CollisionEvents
that contains UnityEvent
properties for each of the different trigger options. Then when I want to hook into a GameObject's OnTrigger functions, I just include the component and drop the function I want it to call in the inspector.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-html -->
public class CollisionEvents : MonoBehaviour {
[field: SerializeField]
public UnityEvent TriggerEnterEvent { get; private set; }
[field: SerializeField]
public UnityEvent TriggerStayEvent { get; private set; }
[field: SerializeField]
public UnityEvent TriggerExitEvent { get; private set; }
public void OnTriggerEnter => TriggerEnterEvent?.Invoke();
public void OnTriggerStay => TriggerEnterEvent?.Invoke();
public void OnTriggerExit => TriggerEnterEvent?.Invoke();
}
<!-- end snippet -->
Doing this allows you to access these functions both in the Inspector like normal Unity Events and in code with collisionEvents.TriggerEnterEvent.addListener()
whilst maintaining a sensible protection level for the property.
I hope this helps answer your question.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论