【问题标题】:Unity enable/disable boolean while playing (editor)Unity 在播放时启用/禁用布尔值(编辑器)
【发布时间】:2020-06-14 10:58:37
【问题描述】:

启用/禁用复选框时的最佳监听方法(在 Unity 编辑器中)?

我想在运行/播放场景时启用和禁用

也许可以切换一次,当我再次单击时编辑器可能会等待? 我不需要每个更新扫描列表..

我的代码:

void Update () {
    checkboxStatus(visibleLocations, locationsList);
}

public void checkboxStatus(bool checkboxEnabled, List<GameObject> list)
{
    if (list.Count > 0) 
    {
        foreach (var item in list)
        {
            if (checkboxEnabled)
            {
                item.GetComponentInChildren<MeshRenderer>().enabled = true;
            }
            else
            {
                item.GetComponentInChildren<MeshRenderer>().enabled = false;
            }
        }
    }
}

【问题讨论】:

    标签: c# unity3d


    【解决方案1】:

    您可以简单地存储和比较以前的值。您还可以可选地添加预处理器,以使 Update 方法仅存在于编辑器中,但稍后在构建中仅使用方法调用(参见 Platform dependent compilation),如

    #if UNITY_EDITOR
        private bool _lastVisibleLocations;
    
        private void Update ()
        {
            if(visibleLocations != _lastVisibleLocations)
            {
                checkboxStatus(visibleLocations, locationsList);
                _lastVisibleLocations = visibleLocations;
            }
        }
    #endif
    
    public void checkboxStatus(bool checkboxEnabled, List<GameObject> list)
    {
        // You can skip the check for Count here
        // if there are no elements then foreach simply will do nothing anyway
        foreach (var item in list)
        {
            // your if-else here was a bit redundant 
            // you can directly use the value of checkBoxEnabled
            item.GetComponentInChildren<MeshRenderer>().enabled = checkBoxEnabled;
        }
    }
    

    如果仅用于编辑器,您甚至可以将其从 Update 移动到 OnValidate,因此仅检查是否通过检查器实际更改了某些内容。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-29
      • 2015-12-05
      • 1970-01-01
      相关资源
      最近更新 更多