Forest_Client/Forest/Assets/Editor/GameBuild/GameBuildHelper.cs

59 lines
2.3 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

using System;
using System.IO;
using UnityEditor;
using Random = UnityEngine.Random;
public class GameBuildHelper
{
private const string BuildSceneTemplate = "Assets/Scenes/BuildTemplate.unity";
[MenuItem("Assets/创建建造场景")]
private static void CreateLevel()
{
var currDir = GetCurrentAssetDirectory().Replace("\\", "/");
var dirName = Path.GetFileName(currDir);
var count = AssetDatabase.FindAssets("t:SceneAsset", new[] { currDir }).Length + 1;
var savePath = GetAssetUniquePath($"{currDir}/{dirName}_{count}.unity", out var assetName);
AssetDatabase.CopyAsset(BuildSceneTemplate, savePath);
var newScene = AssetDatabase.LoadAssetAtPath<SceneAsset>(savePath);
EditorGUIUtility.PingObject(newScene);
}
private static string GetCurrentAssetDirectory()
{
foreach (UnityEngine.Object obj in Selection.GetFiltered<Object>(SelectionMode.Assets))
{
var path = AssetDatabase.GetAssetPath(obj);
if (string.IsNullOrEmpty(path))
continue;
if (System.IO.Directory.Exists(path))
return path;
else if (System.IO.File.Exists(path))
return System.IO.Path.GetDirectoryName(path);
}
return "Assets";
}
/// <summary>
/// 获取一个唯一的路径用于保存asset假设传入的路径已经存在则自动生成一个新的
/// </summary>
/// <param name="assetPath">尝试保存的路径</param>
/// <returns>第一个string是唯一路径第二个string是asset的新名字</returns>
private static string GetAssetUniquePath(string assetPath, out string assetName)
{
assetName = Path.GetFileNameWithoutExtension(assetPath);
var extension = Path.GetExtension(assetPath);
var dir = Path.GetDirectoryName(assetPath);
var savedAsset = AssetDatabase.LoadAssetAtPath<UnityEngine.Object>(assetPath);
if (savedAsset == null)
{
return assetPath;
}
assetName = $"{assetName}_{Random.Range(0, 10000)}";
var newAssetPath = $"{dir}/{assetName}{extension}";
return GetAssetUniquePath(newAssetPath, out assetName);
}
}