Search code examples
unity-game-enginevirtual-reality

Call function from a premade script in Unity


How do I call a function from a Unity (XR Interaction Toolkit) script that's appended to a Ray Interactor? Precisely what I have is a GameObject made as an XR Ray Interactor and appended the XR Direct Interactor script. I want to call the function GetValidTargets from that script to see with what GameObject it targets. How do I call this function in another script? I already have the GameObject specified and tried different methods to implement it, for example GetComponent<>().

This is what the function says in the script so that comes after I call it.

        /// 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)

How do I call this function?


Solution

  • Calling the function if you want to call the function, append the XRBaseInteractable component to every GameObject that you want to able to hover or interact with. Create a List (which are in the System.Collections.Generic namespace), add each XRBaseInteractable instance to it and pass it in to the GetValidTargets() function.

    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);