Unity创建单例脚本工具
程序员文章站
2022-04-03 15:59:43
...
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEditor;
public class ScriptCreatorWindow : EditorWindow
{
[MenuItem("Assets/Create/C# Single Script", false, 1)]
public static void ShowWindow()
{
var window = EditorWindow.GetWindow(typeof(ScriptCreatorWindow));
var screenResolution = Screen.currentResolution;
//left,top to center,center
var w = 300;
var h = 150;
var r = new Rect(screenResolution.width * 0.5f - w * 0.5f, screenResolution.height * 0.5f - h * 0.5f, w, h);
window.position = r;
}
private string scriptName;
void OnGUI()
{
GUILayout.Label("Base Settings", EditorStyles.boldLabel);
scriptName = EditorGUILayout.TextField("Name", scriptName);
if (string.IsNullOrEmpty(scriptName))
{
scriptName = "SingleManager";
}
EditorGUILayout.Space();
if (GUILayout.Button("Create Single"))
{
CreateSingle();
Close();
}
EditorGUILayout.Space();
if (GUILayout.Button("Create Single Mono"))
{
CreateSingleMonoBase();
Close();
}
}
void CreateSingle()
{
string codeSrc = "using System.Collections;\n";
codeSrc += "using System.Collections.Generic;\n";
codeSrc += "using UnityEngine;\n";
codeSrc += "\n";
codeSrc += "public class " + scriptName + " : SingleBase<" + scriptName + ">\n";
codeSrc += "{\n";
codeSrc += " public void Init()\n";
codeSrc += " {\n";
codeSrc += " }\n";
codeSrc += "\n";
codeSrc += " public override void Dispose()\n";
codeSrc += " {\n";
codeSrc += " }\n";
codeSrc += "\n";
codeSrc += "}\n";
var assetPath = string.Format("{0}/{1}{2}", GetSelectedPathOrFallback(), scriptName, ".cs");
var filePath = Application.dataPath.Replace("Assets", assetPath);
File.WriteAllText(filePath, codeSrc);
AssetDatabase.ImportAsset(assetPath);
}
void CreateSingleMonoBase()
{
string codeSrc = "using System.Collections;\n";
codeSrc += "using System.Collections.Generic;\n";
codeSrc += "using UnityEngine;\n";
codeSrc += "\n";
codeSrc += "public class " + scriptName + " : SingleMonoBase<" + scriptName + ">\n";
codeSrc += "{\n";
codeSrc += " protected override void Awake()\n";
codeSrc += " {\n";
codeSrc += " }\n";
codeSrc += "\n";
codeSrc += " protected override void Update()\n";
codeSrc += " {\n";
codeSrc += " }\n";
codeSrc += "\n";
codeSrc += " protected override void OnDestroy()\n";
codeSrc += " {\n";
codeSrc += " }\n";
codeSrc += "\n";
codeSrc += "}\n";
var assetPath = string.Format("{0}/{1}{2}", GetSelectedPathOrFallback(), scriptName, ".cs");
var filePath = Application.dataPath.Replace("Assets", assetPath);
File.WriteAllText(filePath, codeSrc);
AssetDatabase.ImportAsset(assetPath);
}
public static string GetSelectedPathOrFallback()
{
string path = "Assets";
foreach (UnityEngine.Object obj in Selection.GetFiltered(typeof(UnityEngine.Object), SelectionMode.Assets))
{
path = AssetDatabase.GetAssetPath(obj);
if (!string.IsNullOrEmpty(path) && File.Exists(path))
{
path = Path.GetDirectoryName(path);
break;
}
}
return path;
}
}
上一篇: 张辽的实力如何?在曹营能排第几呢?
下一篇: python类共享变量操作