예제 #1
0
        public static T CreateAsset <T>() where T : ScriptableObject
        {
            string selectedDir = SelectionUtility.GetSelectionDir();

            if (string.IsNullOrEmpty(selectedDir))
            {
                selectedDir = "Assets";
            }

            string assetPath = AssetDatabase.GenerateUniqueAssetPath($"{selectedDir}/{typeof(T).Name.ToLower()}.asset");
            T      asset     = ScriptableObject.CreateInstance <T>();

            AssetDatabase.CreateAsset(asset, assetPath);
            AssetDatabase.SaveAssets();

            AssetDatabase.ImportAsset(assetPath);
            SelectionUtility.ActiveObject(asset);
            return(asset);
        }
예제 #2
0
        /// <summary>
        /// 在Project中创建指定类型的资源
        /// 只能创建ScriptableObject类型的资源,对于给定的名称,如果目录中已经存在相同名称的资源,会进行重命名
        /// 创建资源时可以指定资源存储的目录 (assetFolder基于Unity的Assets目录)
        /// </summary>
        /// <typeparam name="T">资源的类型</typeparam>
        /// <param name="fileName">资源名称</param>
        /// <param name="assetFolder">资源存储目录,默认为空</param>
        /// <returns></returns>
        public static T CreateAsset <T>(string fileName, string assetFolder = "") where T : ScriptableObject
        {
            if (fileName.Contains("/"))
            {
                throw new ArgumentException("Base name should not contain slashes");
            }
            if (!string.IsNullOrEmpty(assetFolder) && !assetFolder.StartsWith("Assets"))
            {
                throw new ArgumentException("Asset Folder should be start with Assets");
            }

            string folderPath = string.Empty;

            if (string.IsNullOrEmpty(assetFolder))
            {
                string[] folders = SelectionUtility.GetSelectionDirs();
                if (folders == null || folders.Length == 0)
                {
                    folderPath = "Assets";
                }
                else
                {
                    folderPath = folders[0];
                }
            }
            else
            {
                folderPath = assetFolder;
            }

            var    asset     = ScriptableObject.CreateInstance <T>();
            string assetPath = $"{folderPath}/{fileName}.asset";

            assetPath = AssetDatabase.GenerateUniqueAssetPath(assetPath);

            AssetDatabase.CreateAsset(asset, assetPath);
            AssetDatabase.ImportAsset(assetPath);
            return(asset);
        }