Unity汉化一个插件 制作插件汉化工具

我是编程一个菜鸟,英语又不好,有的插件非常牛!我想学一学,页面全是英文,完全不知所措,我该怎么办啊...

尝试在Unity中汉化一个插件

效果:

请添加图片描述

思路:

如何在Unity中把一个自己喜欢的插件变成中文?在Unity中编写插件一般会用到编辑器扩展
在编辑器扩展中想在Inspector显示自己想要的属性名或者别的什么,就需要用到编辑器扩展的API
把这些固定的API存到一个字典里,例如“EditorGUILayout.PropertyField”,“LabelField”...我可以尝试先读取我们想要汉化插件的Editor文件夹下的每一个代码的每一行
把每一行的每个字符与字典做一个对比
对比成功就说明此行代码可以被汉化,收集可以被汉化的代码行,然后把可以被汉化的代码行替换成我们想要的代码
替换成功后保存代码听起来好像没啥问题,试试看
  • 创建一个存储字典的代码
using System.Collections.Generic;
using UnityEngine;[CreateAssetMenu()]
public class SearchCharacterData : ScriptableObject
{[Header("检索字符对")]public List<Item> items;[Header("添加字符对")]public bool addItem = false;private void OnValidate(){if (addItem){addItem = false;items.Add(new Item());}}/// <summary>/// 物品数据/// </summary>[System.Serializable]public class Item{public string startStr;public string endStr;}
}
  • 完成之后我们就可以在项目中创建一个自定义字典了
    在这里插入图片描述

  • 在字典中添加几对常用AIP用来测试
    在这里插入图片描述

  • 创建一个编辑器窗口代码

using System;
using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEngine;[System.Serializable]
public class Editor_ChinesizationTool : EditorWindow
{private static Editor_ChinesizationTool _window;[MenuItem("Tools/汉化编辑器")]public static void GUIDRefReplaceWin(){Rect wr = new Rect(0, 0, 300, 1000);//窗口大小_window = (Editor_ChinesizationTool)GetWindow(typeof(Editor_ChinesizationTool), true, "汉化编辑");// false 表示不能停靠的_window.Show();}
}
没想到要去翻译一个插件,竟然要自己先写一个...造孽啊~
  • 读文件
	 	/// <summary>/// 读取数据/// </summary>/// <returns></returns>public List<string> ReadFileInfo(bool IsUpdateNewData = true){Datas.Clear();CurrentDatas.Clear();CurrentSplitDatas.Clear();if (IsUpdateNewData) NewSplitDatas.Clear();StreamReader sr = null;//读取string assetsName = FileInfo.FullName;sr = File.OpenText(assetsName.Substring(assetsName.IndexOf("Assets")));//读取文件//读取所有行int line = 0;string data = null;do{data = sr.ReadLine();if (data != null){Datas.Add(data);CurrentDatas.Add(data);foreach (var item in searchCharacterData.items){string csData = FindString(data, item.startStr, item.endStr);if (csData != ""){CurrentSplitDatas.Add(new NewCSData(line, csData));if (IsUpdateNewData) NewSplitDatas.Add(new NewCSData(line, csData));break;}}}line++;} while (data != null);sr.Close();//关闭流sr.Dispose();//销毁流return CurrentDatas;}
  • 将改好的数据进行写入
		void WriteFileInfo(List<string> datas){StreamWriter sw;//写入if (!FileInfo.Exists){Debug.LogError("无法写入,没有该文件");return;}ClearData(path);sw = FileInfo.AppendText();//打开文件foreach (string linedata in datas){sw.WriteLine(linedata);}sw.Flush();//清除缓冲区sw.Close();//关闭流sw.Dispose();//销毁流//ReadFileInfo();}
  • 稍稍修正一下编辑器页面,随便导入一个插件试试看
    在这里插入图片描述

源码

注意!此文件需要放在Editor文件夹下才可以正常使用
using System;
using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEngine;[System.Serializable]
public class Editor_ChinesizationTool : EditorWindow
{private static Editor_ChinesizationTool _window;public string modelPath = "Assets";public List<CSData> cslist = new List<CSData>();public static Rect modelRect;int maxLineCount = 5;Vector2 csDataPos, contentPos;SearchCharacterData searchCharacterData = null;CSData CurrentCSData = null;[MenuItem("Tools/汉化编辑器")]public static void GUIDRefReplaceWin(){Rect wr = new Rect(0, 0, 300, 1000);//窗口大小_window = (Editor_ChinesizationTool)GetWindow(typeof(Editor_ChinesizationTool), true, "汉化编辑");// false 表示不能停靠的_window.Show();}private Material m_material;//1private void OnEnable(){m_material = new Material(Shader.Find("Hidden/Internal-Colored"));//2m_material.hideFlags = HideFlags.HideAndDontSave;//3}void OnGUI(){EditorGUILayout.Space();EditorGUILayout.LabelField("将文件夹拖拽到此处");EditorGUILayout.Space();GUI.SetNextControlName("input1");//设置下一个控件的名字modelRect = EditorGUILayout.GetControlRect();modelPath = EditorGUI.TextField(modelRect, modelPath);EditorGUILayout.Space();DragFolder();EditorGUILayout.Space();searchCharacterData = EditorGUILayout.ObjectField("", searchCharacterData, typeof(SearchCharacterData), true) as SearchCharacterData;// 导出材质if (searchCharacterData == null){GUILayout.Label("请添加字典");return;}if (GUILayout.Button("读取文件")){ReadFile();CurrentCSData = null;}if (CurrentCSData == null){int currentLineCount = 1;csDataPos = EditorGUILayout.BeginScrollView(csDataPos, GUILayout.Width(1000), GUILayout.Height(500));bool isLineEnd = true;maxLineCount = EditorGUILayout.IntField("每行显示脚本的个数", maxLineCount);foreach (CSData csdate in cslist){if (currentLineCount == 1){GUILayout.BeginHorizontal();isLineEnd = false;}if (GUILayout.Button(csdate.name)){CurrentCSData = csdate;}if (currentLineCount == maxLineCount){GUILayout.EndHorizontal();currentLineCount = 0;isLineEnd = true;}currentLineCount++;}if (isLineEnd == false){GUILayout.EndHorizontal();}GUILayout.EndScrollView();}if (CurrentCSData != null){EditorGUILayout.BeginVertical("HelpBox");GUILayout.BeginHorizontal();csDataPos = EditorGUILayout.BeginScrollView(csDataPos, GUILayout.Width(500), GUILayout.Height(700));#region 显示代码int line = 1;lineLocations.Clear();foreach (var date in CurrentCSData.CurrentDatas){GUILayout.Label(line + "  " + date);foreach (var item in CurrentCSData.CurrentSplitDatas){if (line == item.line){LineLocation lineLocation = new LineLocation();Rect rect = GUILayoutUtility.GetLastRect();lineLocation.FirstRect = new Vector2(rect.x, rect.y - csDataPos.y);lineLocation.FirstRectOffset = csDataPos;lineLocations.Add(lineLocation);}}line++;}GUILayout.EndScrollView();GUILayout.Space(100);#endregioncontentPos = EditorGUILayout.BeginScrollView(contentPos, GUILayout.Width(700), GUILayout.Height(700));for (int i = 0; i < CurrentCSData.CurrentSplitDatas.Count; i++){//GUILayout.BeginHorizontal();GUILayout.Label(CurrentCSData.CurrentSplitDatas[i].line + 1 + "  " + CurrentCSData.CurrentDatas[CurrentCSData.CurrentSplitDatas[i].line]);//找到可更换数据lineLocations[i].FirstRect.y += contentPos.y;lineLocations[i].LastRectOffset = contentPos;Rect rect = GUILayoutUtility.GetLastRect();lineLocations[i].LastRect = new Vector2(rect.x, rect.y);CurrentCSData.NewSplitDatas[i].data = EditorGUILayout.TextField(CurrentCSData.NewSplitDatas[i].data);//GUILayout.EndHorizontal();}foreach (var item in lineLocations){m_material.SetPass(0);//4GL.Begin(GL.LINES);GL.Color(Color.red);GL.Vertex3(item.FirstRect.x - 100+10, LimitMax(item.FirstRect.y + 30,690+ item.LastRectOffset.y, item.LastRectOffset.y), 0);GL.Vertex3(item.FirstRect.x - 105+10, LimitMax(item.FirstRect.y + 30, 690+ item.LastRectOffset.y, item.LastRectOffset.y), 0);GL.End();GL.Begin(GL.LINES);GL.Color(Color.black);GL.Vertex3(item.FirstRect.x - 100+10, LimitMax(item.FirstRect.y + 30,690 + item.LastRectOffset.y, item.LastRectOffset.y), 0);//================================================================================================GL.Vertex3(item.LastRect.x-10, LimitMax(item.LastRect.y + 10, 690 + item.LastRectOffset.y, item.LastRectOffset.y), 0); GL.End();GL.Begin(GL.LINES);GL.Color(Color.red);GL.Vertex3(item.LastRect.x-10, LimitMax(item.LastRect.y + 10, 690 + item.LastRectOffset.y, item.LastRectOffset.y), 0);GL.Vertex3(item.LastRect.x-5, LimitMax(item.LastRect.y + 10, 690 + item.LastRectOffset.y, item.LastRectOffset.y), 0);GL.End();//Debug.Log("FirstRect:" + item.FirstRect+"__"+ "LastRect:"+ item.LastRect);//break;}GUILayout.EndScrollView();GUILayout.EndHorizontal();GUILayout.BeginHorizontal();if (GUILayout.Button("确认更改")){CurrentCSData.ReadFileInfo(false);for (int i = 0; i < CurrentCSData.CurrentSplitDatas.Count; i++){CurrentCSData.CurrentDatas[CurrentCSData.CurrentSplitDatas[i].line] =ReplaceStr(CurrentCSData.CurrentDatas[CurrentCSData.CurrentSplitDatas[i].line],CurrentCSData.CurrentSplitDatas[i].data,CurrentCSData.NewSplitDatas[i].data);}for (int i = 0; i < CurrentCSData.Datas.Count; i++){CurrentCSData.Datas[i] = CurrentCSData.CurrentDatas[i];}CurrentCSData.WriterData();AssetDatabase.Refresh();}if (GUILayout.Button("重新选择文件")){CurrentCSData = null;}GUILayout.EndHorizontal();GUILayout.EndVertical();}EditorGUILayout.Space();}List<LineLocation> lineLocations = new List<LineLocation>();public class LineLocation{public Vector2 FirstRectOffset;public Vector2 FirstRect;public Vector2 LastRectOffset;public Vector2 LastRect;}public void ReadFile(){GetAllFilesAndDertorys(modelPath, searchCharacterData);}/// <summary>/// 获得拖拽文件/// </summary>void DragFolder(){//鼠标位于当前窗口if (mouseOverWindow == this){//拖入窗口未松开鼠标if (Event.current.type == EventType.DragUpdated){DragAndDrop.visualMode = DragAndDropVisualMode.Generic;//改变鼠标外观// 判断区域if (modelRect.Contains(Event.current.mousePosition))GUI.FocusControl("input1");}//拖入窗口并松开鼠标else if (Event.current.type == EventType.DragExited){string dragPath = string.Join("", DragAndDrop.paths);// 判断区域if (modelRect.Contains(Event.current.mousePosition))modelPath = dragPath;// 取消焦点(不然GUI不会刷新)GUI.FocusControl(null);}}}static string FindString(string str, string StartStr, string EndStr){if (str.Length < 3)return "";int index3 = str.IndexOf(StartStr);if (index3 != -1){int index4 = str.IndexOf(EndStr, index3);if (index4 != -1){return str.Substring(index3 + StartStr.Length, index4 - index3 - StartStr.Length);}}return "";}void GetAllFilesAndDertorys(string _path, SearchCharacterData searchCharacterData){//判断路径是否存在if (Directory.Exists(_path)){#region 找到Editor文件夹DirectoryInfo dir = new DirectoryInfo(_path);DirectoryInfo[] allDirs = dir.GetDirectories("*", SearchOption.AllDirectories);string EditorPath = "";foreach (var item in allDirs){//忽略.metaif (item.Name.EndsWith(".meta")) continue;string assetsName = item.FullName;assetsName = assetsName.Substring(assetsName.IndexOf("Assets"));if (item.Name == "Editor"){EditorPath = assetsName;break;}}#endregionif (EditorPath != ""){#region 得到Editor文件夹下所有的.cs文件DirectoryInfo editorDir = new DirectoryInfo(EditorPath);cslist.Clear();int ListIndex = 0;foreach (var item in editorDir.GetFiles("*", SearchOption.AllDirectories)){//忽略.metastring assetsName = item.FullName;assetsName = assetsName.Substring(assetsName.IndexOf("Assets"));if (item.Name.EndsWith(".meta")) continue;if (item.Name.EndsWith(".cs")){cslist.Add(new CSData(ListIndex, item, assetsName, searchCharacterData, this));}ListIndex++;}#endregionforeach (var item in cslist){item.ReadFileInfo();}}else{Debug.LogError("该目录没有Editor文件夹");}}}string ReplaceStr(string str, string oldStr, string newStr){if (str.Length < 3)return "";int strIndex = str.IndexOf(oldStr);if (strIndex != -1){string startStr = str.Substring(0, strIndex);string endStr = str.Substring(strIndex + oldStr.Length);return startStr + newStr + endStr;}return "";}public float LimitMax(float f, float maxValue = 690, float minValue = 0){//return f;return Math.Min(maxValue, Math.Max(f, minValue));}[System.Serializable]public class CSData{Editor_ChinesizationTool editor_ChinesizationTool = null;SearchCharacterData searchCharacterData = null;public string name;private FileInfo fileInfo;public int ListIndex = -1;public string path;/// <summary>/// 原始数据/// </summary>public List<string> Datas = new List<string>();/// <summary>/// 当前数据/// </summary>public List<string> CurrentDatas = new List<string>();/// <summary>/// 新数据/// </summary>public List<NewCSData> CurrentSplitDatas = new List<NewCSData>();public List<NewCSData> NewSplitDatas = new List<NewCSData>();public FileInfo FileInfo{get{if (fileInfo == null){editor_ChinesizationTool.ReadFile();fileInfo = editor_ChinesizationTool.cslist[ListIndex].FileInfo;}return fileInfo;}set => fileInfo = value;}public CSData(int mListIndex, FileInfo mfileInfo, string path, SearchCharacterData searchCharacterData, Editor_ChinesizationTool parent){FileInfo = mfileInfo;this.path = path;this.name = FileInfo.Name;this.searchCharacterData = searchCharacterData;this.ListIndex = mListIndex;this.editor_ChinesizationTool = parent;}/// <summary>/// 写入数据/// </summary>public void WriterData(){WriteFileInfo(Datas);}/// <summary>/// 读取数据/// </summary>/// <returns></returns>public List<string> ReadFileInfo(bool IsUpdateNewData = true){Datas.Clear();CurrentDatas.Clear();CurrentSplitDatas.Clear();if (IsUpdateNewData) NewSplitDatas.Clear();StreamReader sr = null;//读取string assetsName = FileInfo.FullName;sr = File.OpenText(assetsName.Substring(assetsName.IndexOf("Assets")));//读取文件//读取所有行int line = 0;string data = null;do{data = sr.ReadLine();if (data != null){Datas.Add(data);CurrentDatas.Add(data);foreach (var item in searchCharacterData.items){string csData = FindString(data, item.startStr, item.endStr);if (csData != ""){CurrentSplitDatas.Add(new NewCSData(line, csData));if (IsUpdateNewData) NewSplitDatas.Add(new NewCSData(line, csData));break;}}}line++;} while (data != null);sr.Close();//关闭流sr.Dispose();//销毁流return CurrentDatas;}void WriteFileInfo(List<string> datas){StreamWriter sw;//写入if (!FileInfo.Exists){Debug.LogError("无法写入,没有该文件");return;}ClearData(path);sw = FileInfo.AppendText();//打开文件foreach (string linedata in datas){sw.WriteLine(linedata);}sw.Flush();//清除缓冲区sw.Close();//关闭流sw.Dispose();//销毁流//ReadFileInfo();}void ClearData(string path){StreamWriter tmpWrite = new StreamWriter(path);tmpWrite.Write("");tmpWrite.Close();}}[System.Serializable]public class NewCSData{public int line = 0;public string data = "";public NewCSData(int line, string data){this.line = line;this.data = data;}}
}

最后的最后:

我自己反正没实践过,可以先拿这个玩玩看还是挺有意思的~
觉得有意思可以改巴改巴,也可以把建议放在评论区,有空我就更新一下~
Demo源码

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/99534.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

nmp ERR! code ERR SOCKET TIMEOUT nmp ERR!network npmSocket timeout(已解决)

当安装vue-cli时&#xff0c;出现超时错误 npm ERR! code ECONNRESET npm ERR! network This is a problem related to network connectivity npm ERR! code ECONNRESET npm ERR! network aborted npm ERR! network This is a problem related to network connectivity. npm E…

如何判断自己的qt版本呢?

如何判断自己的qt版本呢? 前情提要很简单,按照如下图所示,即可查看当前打开的qtCreator的版本如何打开5.15.2版本的qtCreator呢?安装教程 前情提要 我的电脑已经安装了qt5.14.1,然后我又安装了qt5.15.2,我想尝试一下同一台电脑能否适应两个版本的qt? 当我安装完成qt5.15.2后…

Mac Homebrew中常用的 Brew 命令

Mac 中常用的 Brew 命令集 Brew&#xff08;Homebrew&#xff09;是一个强大的包管理器&#xff0c;用于在 macOS 上安装、更新和管理各种软件包。它使得在 Mac 上安装开发工具、应用程序和库变得轻松和便捷。本博客将介绍一些在 Mac 中常用的 Brew 命令&#xff0c;以帮助您更…

Astro建站教程:安装nodejs,npm下载Astro,安装扩展

下载Nodejs LTS版&#xff1a;https://nodejs.org/en 安装步骤全默认即可&#xff0c;安装路径可以根据自己的爱好更改在桌面右键打开cmd或powershell&#xff0c;输入node -v和npm -v测试是否安装成功 浏览器打开https://docs.astro.build/en/install/auto/ 复制里面的npm cre…

MyBatisPlus入门篇2 - 条件查询、查询投影、查询条件、id生成策略、多记录操作、逻辑删除

目录 1.条件查询、多条件查询 MyBatisPlus将书写复杂的SQL查询条件进行了封装&#xff0c;使用编程的形式完成查询条件的组合。 Test void testGetByCondition() {// 方式一&#xff1a;按条件查询QueryWrapper<User> qw new QueryWrapper<User>();qw.lt("…

W5100S_EVB_PICO 做MQTT测试(十二)

前言 上一章我们用W5100S_EVB_PICO 开发板做Ping测试&#xff0c;那么本章我们进行W5100S_EVB_PICO MQTT的测试。 什么是mqtt&#xff1f; MQTT&#xff08;Message Queuing Telemetry Transport&#xff0c;消息队列遥测传输协议&#xff09;&#xff0c;是一种基于发布/订…

Lua语法结构

Lua基础 注释 print("hello.") -- 单行注释的写法 --[[ 多行注释的写法 --]]标识符 关键字 **and **break**do **else**elseif ****end **falsefor**function **ifinlocalnilnotorrepeatreturnthentrueuntil**while ** 数据类型 nil** boolean**** number**** st…

计算机网络的故事——确保Web安全的Https

确保Web安全的Https 文章目录 确保Web安全的Https一、HTTP 的缺点二、HTTP 加密 认证 完整性保护 HTTPS 一、HTTP 的缺点 1、明文传输 通信加密&#xff0c;HTTP协议中没有加密机制&#xff0c;但是可以通过SSL(Secure Socket Layer&#xff0c;安全套接字层)或TLE(Transpor…

算法做题记录

一、递推 95.费解的开关 #include<iostream> #include<cstring> using namespace std;const int N 8;char a[N][N],s[N][N]; int T; int ans20,cnt; int dir[5][2]{1,0,-1,0,0,1,0,-1,0,0};void turn(int x,int y) {for(int i0;i<5;i){int xx xdir[i][0];in…

在MySQL中查看数据库和表的数据大小

在MySQL中查看数据库和表的数据大小 在管理和维护MySQL数据库时&#xff0c;了解数据库和表的数据大小是非常重要的。这可以帮助您监控数据库的增长、优化性能以及规划存储需求。本博客将介绍如何使用SQL查询来查看MySQL数据库和表的数据大小。 查看MySQL数据库的总数据大小 …

【开发语言】C语言与Python的互操作详解

博主未授权任何人或组织机构转载博主任何原创文章&#xff0c;感谢各位对原创的支持&#xff01; 博主链接 本人就职于国际知名终端厂商&#xff0c;负责modem芯片研发。 在5G早期负责终端数据业务层、核心网相关的开发工作&#xff0c;目前牵头6G算力网络技术标准研究。 博客…

vscode debug python launch.json添加args不起作用

问题 为了带入参数调试python 程序&#xff0c;按照网上搜到的教程配置了lauch.json文件&#xff0c;文件中添加了"args": [“model” “0” “path”] {// 使用 IntelliSense 了解相关属性。 // 悬停以查看现有属性的描述。// 欲了解更多信息&#xff0c;请访问: h…