まず、Unityにガベージコードを追加します。まず、大手ブロガーを参照してください。https://blog.csdn.net/linxinfa/article/details/115299584
生成後、その基盤に基づいて動的にスクリプトを生成し始めました
。最初はすべてのガベージ機能
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using System.Linq;
using UnityEditor;
using System;
using System.Text;
public static class RubbishList
{
public static List<string> List = new List<string>();
}
public class MyToolCreateScript
{
static string myFilePath = "/MyScripts/RubbishXiaoHuang.cs";
private static string className;
private static string folderName = "/Scripts/output";
[MenuItem("小黄/垃圾代码调用")]
static void UseRubbishCodeToMono()
{
CheckFilecs();
CreateCode();
}
private static void CheckFilecs()
{
folderName = Application.dataPath + folderName;
DirectoryInfo CSFile = new DirectoryInfo(folderName);
foreach (FileInfo file in CSFile.GetFiles())
{
if (file.Name.EndsWith(".cs"))
{
Debug.Log(file.Name.Substring(0, file.Name.IndexOf(".")));
string myscript = file.Name.Substring(0, file.Name.IndexOf("."));
RubbishList.List.Add(myscript);
}
}
}
static void CreateCode()
{
string realPath = Application.dataPath + myFilePath;
var fs = new FileStream(realPath, FileMode.OpenOrCreate);
if(!fs.CanWrite)
{
Debug.LogError("无法写入文件");
return;
}
string data = CreateClass(true);
var bytes = Encoding.UTF8.GetBytes(data);
Debug.Log("class长度:" + bytes.Length);
fs.Write(bytes, 0, bytes.Length);
fs.Flush();
fs.Close();
}
private static string CreateClass(bool v)
{
StringBuilder sb = new StringBuilder();
sb.Append(CreateUsing());
var str = CreateClassHead(true,"RubbishXiaoHuang");
sb.Append(str);
sb.Append(CreateMethodStart());
sb.Append(CreateClassEnd());
return sb.ToString();
}
private static string CreateUsing()
{
StringBuilder sb = new StringBuilder();
sb.Append("using UnityEngine;\nusing System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Text;");
return sb.ToString();
}
static string CreateClassHead(bool implementMono, string className)
{
string str = implementMono ? ":MonoBehaviour" : "";
return "\npublic class " + className + str + "\n{";
}
static string CreateClassEnd()
{
string str = "\n}";
return str;
}
static string CreateMethodStart()
{
StringBuilder sb = new StringBuilder();
sb.Append("\nvoid Start()\n{\n");
for(int i=0;i<RubbishList.List.Count;i++)
{
int k = i;
string str = RubbishList.List[k].ToString() + "\t" + RubbishList.List[k].ToLower() + "=new\t" + RubbishList.List[k] + "( );\n";
sb.Append(str);
}
sb.Append("}");
return sb.ToString();
}
[MenuItem("小黄/生成挂在垃圾代码物体")]
static void CreateGameObject()
{
if(File.Exists(Application.dataPath+myFilePath))
{
GameObject ScripGameObject = new GameObject("垃圾");
}
else
{
Debug.Log("不存在该脚本");
}
}
}
最後に、garbageという名前のオブジェクトをスクリプトにフックすることは、ガベージコードのいくつかのインターフェイスを呼び出すことと同じです。監査に合格したかどうかはまだテストしていません。