mrtkwindows-mixed-reality

Using FocusHandler.OnFocusEnter(FocusEventData) method to recolour objects based on time passed


I'm having some trouble with the FocusHandler.OnFocusEnter(FocusEventData) Method. I hope someone can help me. A bit of a newbie here to the MRTK2 toolkit. I want to recolour a cube based on the time it is focused on but am having trouble to incorporate the time component.

With the following code, the stateProperties of the InteractableColorTheme of the cube are adjusted properly when focused on.:

   public void OnFocusEnter(FocusEventData eventData)
    {
        var colorTheme = this.GetComponent<Interactable>().ActiveThemes[0];
        colorTheme.StateProperties[0].Values[0].Color = Color.green; //set color of default state
        colorTheme.StateProperties[0].Values[1].Color = Color.red; //set color of focus state
        colorTheme.StateProperties[0].Values[2].Color = Color.yellow; //set color of pressed stat
    }

So far, so good. When this is ran, the colorTheme properties are directly updated and displayed. However, I'm running into trouble when introducing the time component. I was unable to implement a timer directly inside OnFocusEnter in order to change the stateProperties after x amount of time has passed while focusing on the object. I'm assuming this method is not updated every frame.

As a workaround I created a bool that is set to true when the OnFocusEnter event fires. In Update(), the time passed is checked if this bool is true, which then sets the StateProperties of the theme corresponding to the amount of time passed. Example for 3 seconds passed:

     if (timePassed > 3)
      {
        var colorTheme = this.GetComponent<Interactable>().ActiveThemes[0];
        colorTheme.StateProperties[0].Values[1].Color = Color.green;
      }

While with this code I do see that in the inspector, the stateProperties are actually changing after 3 seconds have passed, but the object appearance is not actually updated unless focus is first lost and then the object is focused on again. What's going wrong here? I can't seem to figure it out.

Any help is much appreciated!


Solution

  • Your second piece of code just modifies the profile of the visual theme and does not modify the color of the material. The visual theme will only respond when the interaction state changes, please refer to Visual themes - MRTK 2 | Microsoft Learn.

    Here MRTK modifies the color via MaterialPropertyBlock, you can also modify it manually, refer to the code below.

    var block = new MaterialPropertyBlock();
    block.SetColor(“_Color”, Color.blue);
    GetComponent<MeshRenderer>().SetPropertyBlock(block);