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目录下。
转载请注明出处...