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和编程方面的知识。

相关推荐
June bug8 小时前
【领域知识】休闲游戏一次发版全流程:Google Play + Apple App Store
unity
星夜泊客10 小时前
C# 基础:为什么类可以在静态方法中创建自己的实例?
开发语言·经验分享·笔记·unity·c#·游戏引擎
dzj202111 小时前
PointerEnter、PointerExit、PointerDown、PointerUp——鼠标点击物体,则开始旋转,鼠标离开或者松开物体,则停止旋转
unity·pointerdown·pointerup
心前阳光12 小时前
Unity 模拟父子关系
android·unity·游戏引擎
在路上看风景15 小时前
26. Mipmap
unity
咸鱼永不翻身17 小时前
Unity视频资源压缩详解
unity·游戏引擎·音视频
在路上看风景17 小时前
4.2 OverDraw
unity
在路上看风景18 小时前
1.10 CDN缓存
unity
ellis19701 天前
Unity插件SafeArea Helper适配异形屏详解
unity
nnsix1 天前
Unity Physics.Raycast的 QueryTriggerInteraction枚举作用
unity·游戏引擎