Unity 简单随机创建玩家游戏名

using UnityEngine;
using System.Collections;
using System;

public class RandomName {

    //形容词跟名字的下标
    private static int nameIndex = 0;
    private static int adjIndex = 0;

    //两个保存随机游戏名的数组
    private static string[] names;
    private static string[] adjectives;
    
    //两个随机对象
    private static System.Random nameRandom;
    private static System.Random adjectiveRandom;

    public static void  LoadPlayerNameText()
    {
        //从Resource读取txt文件,文件格式为utf-8(中文)
        TextAsset namesAsset = (TextAsset)Resources.Load("name", typeof(TextAsset));
        TextAsset adjectiveAsset = (TextAsset)Resources.Load("adjective", typeof(TextAsset));

       
        if (namesAsset.text != null && namesAsset.text.Length > 0)
        {
            string content = namesAsset.text;
            names = content.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries); //忽略空行
        }

        if (adjectiveAsset.text != null && adjectiveAsset.text.Length > 0)
        {
            string content = adjectiveAsset.text;
            adjectives = content.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
        }

        if (names != null && names.Length > 0)
        {
            nameRandom = new System.Random();
        }

        if (adjectives != null && adjectives.Length > 0)
        {
            adjectiveRandom = new System.Random();
        }

    }


    //获取随机名
    public static string getRandomName()
    {
        if (nameRandom != null)
        {
            nameIndex = nameRandom.Next(0, names.Length);
        }

        if (adjectiveRandom != null)
        {
            adjIndex = adjectiveRandom.Next(0, adjectives.Length);
        }

        string playerName = "";
        if (adjIndex >= 0 && nameIndex >= 0)
        {
              playerName = adjectives[adjIndex] + names[nameIndex];
        }
        return playerName;
    }
}



游戏运行时,先执行第一个方法,之后就可以使用第二个方法获取随机名,这里两个txt文件得自己好,格式如下:

小明

小李

小花

格式可自己定,只要content.splite()方法就行

最后注意一点就是,txt文件需要放在Resource目录下。


转载请注明出处...



  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值