版权声明:本文为博主原创文章,转载请注明出处。 https://blog.csdn.net/qq563129582/article/details/83271627
一个随机数的软件,可手动输入最大值,可用于课堂上随机点名,单个学生可随机多次。
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class RandomIndex : MonoBehaviour {
public InputField input;//手动输入最大值
public Text numText;//显示text
private int MinNum = 1;//默认最小值
private int MaxNum = 50;//默认最大值
private int MaxTimes = 1;//一个数字最多出现次数
private int random = 0;//当前随机数
void Start () {
}
void Update()
{
//清空所有记录,重新开始计数
if (Input.GetKey(KeyCode.C) && Input.GetKey(KeyCode.LeftControl))
{
ClearAllData();
numText.text = "清空数据完毕!";
}
//退出程序
if (Input.GetKeyDown(KeyCode.Escape))
{
Application.Quit();
}
}
public void ClearAllData()
{
PlayerPrefs.DeleteAll();
numText.text = "清空数据完毕!";
}
public void RandomClick()
{
if (input.text != null && input.text != "")
{
MaxNum = int.Parse(input.text);
}
random = Random.Range(MinNum, MaxNum);
int randomTimes = 0;
while (true)
{
//防止死循环
randomTimes++;
if (randomTimes > 100)
{
numText.text = "没有可随机的学生了,请重新开始!";
break;
}
int times = SaveIndex(random);
if (times > MaxTimes)
{
random++;
if (random >= MaxNum)
{
random = 1;
}
continue;
}
numText.text = "随机" + random+ "号,第"+ times+"次";
break;
}
}
int SaveIndex(int num)
{
string IdKey = "STUDENT" + num;
int count = 1;
if (!PlayerPrefs.HasKey(IdKey))
{
PlayerPrefs.SetInt(IdKey, count);
}
else
{
count = PlayerPrefs.GetInt(IdKey, 1);
count++;
PlayerPrefs.SetInt(IdKey, count);
}
return count;
}
}