NG_/Assets/Scripts/其他/RandomNum.cs
2024-12-13 19:40:05 +08:00

47 lines
1.4 KiB
C#

using System.Collections;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using UnityEngine;
using UnityEngine.UI;
public class RandomNum : MonoBehaviour
{
public float maxNum=30;
public float minNum=-20;
public float jiaJian=0.1f;
// Update is called once per frame
void OnEnable()
{
StartCoroutine(ChangeAir());
}
private IEnumerator ChangeAir()
{
while (true) // 无限循环
{
// 获取当前文本
string originalText = gameObject.GetComponent<Text>().text;
// 使用正则表达式提取所有数字
string pattern = @"-?\d+(\.\d+)?";
MatchCollection matches = Regex.Matches(originalText, pattern);
// 遍历所有找到的数字并修改
foreach (Match match in matches)
{
float originalNumber = float.Parse(match.Value);
if (Random.Range(0, 10) < 2&&originalNumber>minNum)originalNumber=originalNumber-jiaJian;
if (Random.Range(0, 10) >7&&originalNumber<maxNum)originalNumber=originalNumber+jiaJian;
originalText = originalText.Replace(match.Value, originalNumber.ToString("F1"));
}
gameObject.GetComponent<Text>().text = originalText;
int time = Random.Range(2, 5);
yield return new WaitForSeconds(time); // 等待两秒
}
}
}