Unity自己实现的中英文的切换(简单好抄)

关键技术(读取文件的方法,Split()分割字符串)

1.搭建一个这样的场景,场景中有3个文本(用新版的),一个空对象,一个按钮

2.编写翻译文本(编写一个txt文本,在文本编写你翻译要用的文字,用:分开(注意这是英文分号),自己记住这个文件保存的位置)

3.编写脚本(注意把翻译文本替换成你自己文件的位置)

cs 复制代码
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using TMPro;
using Unity.VisualScripting;
using UnityEngine;

public class CreateMap2 : MonoBehaviour
{
    private bool chanese=true;
    //这是切换语言的练习
    void Start()
    {
        // 查找场景中所有的 TextMeshProUGUI 组件
        TextMeshProUGUI[] allTexts = FindObjectsOfType<TextMeshProUGUI>();
        // 遍历数组,并打印每个 TextMeshProUGUI 的文本内容
        foreach (TextMeshProUGUI text in allTexts)
        {
            Debug.Log(text.text);
        }
    }
    public void change(){
        Encoding encoding = Encoding.UTF8;//读取格式
        string filePath = @"E:\text\Language.txt";//这里换成你自己的文件位置
        string fileContent = File.ReadAllText(filePath, encoding);//读取文件 
        string str = fileContent;
        string[] parts = str.Split('\n');//将所有文本第一次分割
        // 查找场景中所有的 TextMeshProUGUI 组件
        TextMeshProUGUI[] allTexts = FindObjectsOfType<TextMeshProUGUI>();
        //Debug.Log(parts[0]);
        if (chanese == true)
        {
            for (int i = 0; i < parts.Length; i++)
            {
                string str2 = parts[i];
                string[] parts2 = str2.Split(':');
                foreach (TextMeshProUGUI text in allTexts)
                {
                    if (text.text == parts2[0])//如果一开始就是中文就转换为英文
                    {
                        text.text = parts2[1].ToString();
                    }
                }
            }
            chanese = false;
        }
        else {
            for (int i = 0; i < parts.Length; i++)
            {
                string str2 = parts[i];
                string[] parts2 = str2.Split(':');
                foreach (TextMeshProUGUI text in allTexts)
                {
                    if (text.text == parts2[1])//如果一开始就是中文就转换为英文
                    {
                        text.text = parts2[0].ToString();
                    }
                }
            }
            chanese = true;
        }
    }
}

4.将脚本拖到空对象上,并给按钮绑定事件

5.运行游戏点击按钮就能看到翻译效果了(连续点击会在中英文之间切换)

如果这些内容对大家有用的话,希望大家点个关注或者点个赞也行(点赞越多更新越快), 以后不定期更新自己学习unity和编程方面的知识。

相关推荐
JIes__1 小时前
Unity(二)——MonoBehavior中的重要内容
unity·游戏引擎
孟无岐7 小时前
【Laya】LocalStorage 本地存储
typescript·游戏引擎·游戏程序·laya
妙为15 小时前
unreal engine5角色把敌人 “挤飞”
游戏引擎·虚幻·ue·unrealengine5
4Forsee15 小时前
【增强现实】快速上手 Vuforia Unity Android AR 应用开发
android·unity·ar
两水先木示15 小时前
【Unity】对指定物体进行描边——模板测试法
unity·游戏引擎·shader·外描边
Miss_SQ16 小时前
实现Unity录音、百度云语音转文字
unity·语音识别
CreasyChan16 小时前
unity 对象池实测可用
unity·c#
weixin_4242946716 小时前
Unity项目的Artifacts文件夹过大怎么解决?
unity·游戏引擎
没事写写笔记1 天前
Unity HDRP14.0.12 Volume 配置参数
unity
红黑色的圣西罗1 天前
手游手动异形屏适配方案,类“明日方舟”
unity