[转]脚本生成Preset Libraries

Preset Libraries它干的事就是把若干个颜色值保存起来。我们都知道颜色值用rgba来保存的。这样拷贝起来就很麻烦了,如果说我把每个界面的颜色都做成模板,需要设置颜色的时候在模板里选择多好?unity提供了Preset Libraries 就可以达到这个需求。 http://docs.unity3d.com/Manual/PresetLibraries.html

但是问题来了,这东西不能通过脚本来自动化完成,总不能手动的一个一个设置吧。。。我想做的就是用脚本来创建Preset Libraries,找了半天也没找到官方提供的API。那么没办法只能自己来了。直接上代码。

using UnityEngine;
using UnityEditor;
using System;
using System.Collections.Generic;
 
 
public class Test  {
 
 
    public class ColorData
    {
        public string name;
        public Color color;
    }
    
 
    [MenuItem("Tool/Creat Color")]
    static void Build () 
    {
 
        //复制一份新的模板到newColorPath目录下
        string templateColorPath="Assets/Template/color.colors";
        string newColorPath="Assets/Editor/界面1.colors";
        AssetDatabase.DeleteAsset(newColorPath);
        AssetDatabase.CopyAsset(templateColorPath,newColorPath);
        AssetDatabase.SaveAssets();
        AssetDatabase.Refresh();
 
 
    
        //这里我写了两条临时测试数据
        List<ColorData>colorList = new List<ColorData>(){
            new ColorData(){name ="按钮样式1颜色",color = Color.green},
            new ColorData(){name ="按钮样式2颜色", color =new Color(0.1f,0.1f,0.1f,0.1f)}
 
        };
 
        UnityEngine.Object newColor = AssetDatabase.LoadAssetAtPath<UnityEngine.Object>(newColorPath);
        SerializedObject serializedObject = new SerializedObject(newColor);
        SerializedProperty property = serializedObject.FindProperty("m_Presets");
        property.ClearArray();
 
        //把我的测试数据写进去
        for(int i =0; i< colorList.Count; i++){
            property.InsertArrayElementAtIndex(i);
            SerializedProperty colorsProperty = property.GetArrayElementAtIndex(i);
            colorsProperty.FindPropertyRelative("m_Name").stringValue = colorList[i].name;
            colorsProperty.FindPropertyRelative("m_Color").colorValue = colorList[i].color;
        }
        //保存
        serializedObject.ApplyModifiedProperties();
        AssetDatabase.SaveAssets();
        AssetDatabase.Refresh();
    }
 
}

因为我并不知道它的.colors的序列化类对象结构。所以我在Color界面中Presets->Create New Library,Location中选择本地Project。这时候.colors文件就生成在Editor下面了,然后我把它拷贝到Template文件夹下用来做我的模板。 然后我通过这个模板,再加上颜色的数据信息来生成我的.colors文件数据,图中“界面1”就是我生成出来的。 (这里可以用中文)

生成出来之后,在选择颜色的时候就可以设置模板里的颜色啦。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,180评论 25 708
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,228评论 4 61
  • 若现在有人问你的梦想是什么,你要不就觉得像是歌唱节目导师的问话,要不就是嗤之以鼻嘲笑你还说梦想,或者你会发现你没有...
    我是狐狸一只阅读 212评论 0 2
  • 看了老师关于猫的故事,不由自主地勾起了我伤心的回忆…… 举世瞩目的唐山大地震前,我在上小学。我家离学校很近,有一位...
    海迪哲lshj阅读 308评论 3 5
  • 挫败感会累积 累积到没有了骄傲 没有沾沾自喜春风得意
    GUIYEWANSHAN阅读 110评论 0 0