kingBook

导航

UnityEditor 代码创建与编辑预制件

  • 在编辑器模式下创建预制件
#if UNITY_EDITOR

using UnityEditor;
using UnityEngine;

public class EditorTest : Editor {

    [MenuItem("Tools/EditorTest", true)]
    private static bool ValidateMenuItem() {
        return !EditorApplication.isPlaying;
    }

    [MenuItem("Tools/EditorTest")]
    private static void Test() {
        if (EditorApplication.isPlaying) return;
        Debug.Log("== Tools/EditorTest ==");

        // 在当前场景中创建对象"AA"
        var inst = new GameObject("AA");

        string prefabPath = $"Assets/{inst.name}.prefab";

        // 将对象存储为预制件,但与实例不关联
        PrefabUtility.SaveAsPrefabAsset(inst, prefabPath);

        // 将对象存储为预制件,并与实例保持关联,InteractionMode.UserAction 时 可通过 ctrl+z 撤销关联
        //PrefabUtility.SaveAsPrefabAssetAndConnect(inst, prefabPath, InteractionMode.AutomatedAction);
        //PrefabUtility.SaveAsPrefabAssetAndConnect(inst, prefabPath, InteractionMode.UserAction);

        // 删除实例
        DestroyImmediate(inst);
    }
}
#endif
  • 修改场景中已关联的预制件实例
// 是否处于预制件模式,获取预制件模式的预制件路径
PrefabStage prefabStage = PrefabStageUtility.GetCurrentPrefabStage();
if (prefabStage != null) {
    Debug.Log("处于预制件模式");
    Debug.Log($"预制件模式修改的预制件路径:{prefabStage.prefabAssetPath}");
    
    // 预制件模式下,在当前修改的预制件下创建 GameObject
    var go = new GameObject("aa");
    go.transform.parent = prefabStage.prefabContentsRoot.transform;
    
    
    #region 在 UGUI 预制件下创建 Image
    var parent = prefabStage.prefabContentsRoot.transform.Find("PanelJigSaw/SafeAreaGroup/RootGroup/Images10");

    var inst = new GameObject($"Image (1)",typeof(RectTransform),typeof(Image));
    inst.transform.SetParent(parent);

    // 更改 Image 组件的 Sprite
    var image = inst.GetComponent<Image>();
    image.sprite = AssetDatabase.LoadAssetAtPath<Sprite>("Assets/Textures/PanelJigSaw/10/5.png");
    image.SetNativeSize();

    // 更改 Width 和 Height
    var rectTransform = inst.GetComponent<RectTransform>();
    rectTransform.sizeDelta = rectTransform.sizeDelta * 0.28f;
    #endregion 在 UGUI 预制件下创建 Image
    
}

posted on 2022-02-15 16:14  kingBook  阅读(654)  评论(0编辑  收藏  举报