You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MRTK2中聚焦时长控制物体颜色,修改属性后外观不更新求助

问题原因及解决方案

问题根源

直接修改InteractableColorTheme的StateProperties颜色值后,MRTK的Interactable组件未感知到属性变更,不会实时重新计算并应用主题样式,只有聚焦状态重新触发时才会刷新外观。

解决方法

方法1:强制刷新Interactable

修改颜色后调用Interactable.Refresh()方法,强制组件重新应用主题配置:

if (timePassed > 3)
{
    var interactable = this.GetComponent<Interactable>();
    var colorTheme = interactable.ActiveThemes[0];
    colorTheme.StateProperties[0].Values[1].Color = Color.green;
    // 触发主题刷新
    interactable.Refresh();
}

方法2:使用规范的主题属性修改API

用Interactable.SetThemeProperty()方法修改颜色,该方法内部会自动处理属性变更通知和样式刷新,更符合MRTK的设计规范:

if (timePassed > 3)
{
    var interactable = this.GetComponent<Interactable>();
    // 定位颜色主题的索引
    var colorThemeIndex = interactable.ActiveThemes.FindIndex(t => t is InteractableColorTheme);
    if (colorThemeIndex != -1)
    {
        // 参数:主题索引、属性名、目标状态、颜色值
        interactable.SetThemeProperty(colorThemeIndex, "Color", InteractableState.Focus, Color.green);
    }
}

优化计时逻辑

避免每帧重复修改颜色,增加状态标记控制:

private bool isFocused = false;
private float timePassed = 0f;
private bool hasChangedColor = false;

public void OnFocusEnter(FocusEventData eventData)
{
    isFocused = true;
    timePassed = 0f;
    hasChangedColor = false; // 重新聚焦时重置标记
}

public void OnFocusExit(FocusEventData eventData)
{
    isFocused = false;
    timePassed = 0f;
}

void Update()
{
    if (isFocused && !hasChangedColor)
    {
        timePassed += Time.deltaTime;
        if (timePassed > 3f)
        {
            hasChangedColor = true;
            var interactable = GetComponent<Interactable>();
            var colorTheme = interactable.ActiveThemes[0];
            colorTheme.StateProperties[0].Values[1].Color = Color.green;
            interactable.Refresh();
        }
    }
}

内容的提问来源于stack exchange,提问作者Keo95

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 11:42:17