Search code examples
c#unity-game-enginemrtk

How to place a prefab and then remove it via voice when looked at


User can place objects (prefabs) at runtime using hands/gaze. Voice command ""Remove" should remove the current focussed (looked at) object.

I tried instantiating the objects and adding the Intractable script. But I am stuck add adding OnfocusEnter and OnfocusExit events at runtime.

Hooking up the events on the prefab wont work as the references are in the scene.


Solution

  • Based on @jShull answer I came up with a simple solution for what I needed. Since there is no global listener for focus events I basically made my own.

    I also added an earlier discussion (before I posted the question here) with two Microsoft Developers of the Mixed Reality Toolkit which could help out of you are looking for more functionality: https://github.com/microsoft/MixedRealityToolkit-Unity/issues/4456

    "Object" script that is a component of the object that needs to be removed or interacted with.

    using Microsoft.MixedReality.Toolkit.Input;
    using UnityEngine;
    
    public class Object: MonoBehaviour, IMixedRealityFocusHandler
    {
        public GameManager _gameManager;
    
        public void OnFocusEnter(FocusEventData eventData)
        {
            Debug.Log("Focus ON: " + gameObject);
            _gameManager.SetFocussedObject(gameObject);
        }
    
        public void OnFocusExit(FocusEventData eventData)
        {
            Debug.Log("Focus OFF: " + gameObject);
            _gameManager.ResetFocussedObject();
        }
    }
    

    "GameManager" script functions that sets the focussedObject

    public void SetFocussedObject(GameObject object)
    {
        focussedObject = object;
    }
    
    public void ResetFocussedObject()
    {
        focussedObject = null;
    }
    

    Remove Object function is connect to the "Remove" global speech command in the "Speech Input Handler" component. It just removes the "focussedObject" inside the GameManager.