首页 > 解决方案 > 从 Unity 中的预制脚本调用函数

问题描述

如何从附加到 Ray Interactor 的 Unity(XR 交互工具包)脚本中调用函数?我所拥有的正是一个作为 XR 射线交互器制作的游戏对象,并附加了 XR 直接交互器脚本。我想从该脚本调用函数 GetValidTargets 以查看它的目标游戏对象。如何在另一个脚本中调用此函数?我已经指定了 GameObject 并尝试了不同的方法来实现它,例如 GetComponent<>()。

这就是函数在脚本中所说的内容,所以在我调用它之后就会出现。

        /// Retrieve the list of interactables that this interactor could possibly interact with this frame.
        /// This list is sorted by priority (in this case distance).
        /// <param name="validTargets">Populated List of interactables that are valid for selection or hover.</param>
        public override void GetValidTargets(List<XRBaseInteractable> validTargets)

我如何调用这个函数?

标签: unity3dvirtual-reality

解决方案


如果要调用该函数,请调用该函数,将XRBaseInteractable组件附加到您希望能够悬停或与之交互的每个游戏对象。创建一个 List(位于 System.Collections.Generic 命名空间中),将每个 XRBaseInteractable 实例添加到其中并将其传递给 GetValidTargets() 函数。

GameObject[] interactableObjects; // Set in inspector or somewhere in code
List<XRBaseInteractable> interactables = new List<XRBaseInteractable>();
foreach(GameObject interactableObject in interactableObjects)
{
    interactables.Add(interactableObject.GetComponent<XRBaseInteractable>());
}
GetComponent<XRDirectInteractor>().GetValidTargets(interactables);

推荐阅读