Unity---批量修改UI预设组建的属性,并保存预设

文章目录

      • 批量修改预设并及时保存
      • 批量修改UI预设

批量修改预设并及时保存

用代码批量修改预设属性,修改后,在属性面板属性值也立即改变了,对于大量的预设的修改,效率会提高,不需要手动Apply预设。

调用Editor下的工具类的方法SetDirty(GameObject),将修改过的预设设置为Dirty,Unity会自动保存修改过的预设。

EditorUtility.SetDirty(GameObject)

Unity 官网对这个接口的解释:

Marks target object as dirty.

Unity internally uses the dirty flag to find out when assets have changed and need to be saved to disk.

E.g. if you modify a prefab’s MonoBehaviour or ScriptableObject variables, you must tell Unity that the value has changed. Unity builtin components internally call SetDirty whenever a property changes. MonoBehaviour or ScriptableObject don’t do this automatically so if you want your value to be saved you need to call SetDirty.

批量修改UI预设

批量修改UI预设下的所有Image, Text组建的RacastTarget属性。

在UI层,Image, Text组建除了做为按钮,其他的时候基本上不参与事件响应了,不需要参与射线检测。

MenuItem("Assets/ModifyImageAndTextRaycastTarget")
static void ModifyUIImageAndTextRaycastAttribute()
{
    Object[] selectedObjs = Selection.GetFiltered(typeof(GameObject),SelectionMode.DeepAssets);
    for(int i = 0 ; i < selectedObjs.Length;i++)
    {
        go = selectedObjs[i] as GameObject;
        var imgs = go.GetComponentsInChildren(true);
        for(int j = 0; j < imgs.Length;j++)
        {
             Image img = imgs[j];
             img.raycastTarget = false;
        }
        var texts = go.GetComponentsInChildren(true);
        for(int j = 0 ; j < texts.Length;j++)
        {
            Text text = texts[j];
            if(text.transform.parent != null)
            {
                if(text.transform.parent.GetComponent() == null)
                    text.raycastTarget = false;
                else
                    text.raycastTarget = true;
                
            }
            else
            {
                 text.raycastTarget = false;
            }
        }
        Debug.Log(string.Format("已修改{0}预设Image和Text组建的Raycast",go.name));
        EditorUtility.SetDirty(go);
    }
}

你可能感兴趣的:(Unity3D)