Search code examples
c#unity-game-enginehololenswindows-mixed-reality

Checkbox not working as intended in Mixed reality toolkit V2


Checkboxes are currently unusable in the new toolkit, as you cannot bind functions to states.

There is a development commit on GitHub, but it's not usable yet, so I need a script to work around, without changing the toolkit.

Should be able to easily set starting state, and call functions on state change - which you currently can't.


Solution

  • Found a solution that works without changing the toolkit, and should work on newer versions.

    using UnityEngine;
    using Microsoft.MixedReality.Toolkit.UI;
    using UnityEngine.Events;
    
    [RequireComponent(typeof(Interactable))]
    public class CheckBoxInteractableSwitch : MonoBehaviour
    {
    
        public bool startChecked = true;
    
        public UnityEvent OnCheck;
        public UnityEvent OnUncheck;
    
        private Interactable interactable;
        private int state = 1;
    
        void Start()
        {
            interactable = GetComponent<Interactable>();
    
            if (OnCheck == null)
                OnCheck = new UnityEvent();
            if (OnUncheck == null)
                OnUncheck = new UnityEvent();
    
            OnCheck.AddListener(Checked);
            OnUncheck.AddListener(UnChecked);
    
            //works with 2 dimensions only
            if (startChecked)
            {
                if (interactable.GetDimensionIndex() == 0) interactable.IncreaseDimension();
            }
            else
            {
                if (interactable.GetDimensionIndex() == 1) interactable.IncreaseDimension();
            }
    
        }
    
        void Update()
        {
            if (interactable == null) return;
    
            //state check
            if (state != interactable.GetDimensionIndex())
            {
                state = interactable.GetDimensionIndex();
                if (state == 0) OnUncheck.Invoke();
                if(state == 1) OnCheck.Invoke();
            }
        }
    
        private void Checked()
        {
    
        }
    
        private void UnChecked()
        {
    
        }
    }
    

    Works with checkboxes only (2 dimension), you can set the default state for the checkbox, and you can subscribe to states on state changes.