其他分享
首页 > 其他分享> > Unity随机点名案例

Unity随机点名案例

作者:互联网

效果:

做了个 随机点名的小功能,希望能给新人们一些帮助~
在这里插入图片描述


0积分下载


实现代码:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;

public class NewBehaviourScript : MonoBehaviour
{
    [SerializeField] private List<string> names;
    [SerializeField] private float RunTime = 3f;//运行时间
    private float RuningTime = 0f;//已运行时间
    private float AddTime = 0.02f;//名字跳动间隔时间
    [SerializeField] [Tooltip("开始点名按钮")] private Button StartButton;
    [SerializeField] [Tooltip("显示名字的Text")] private Text ShowNameText;
    /*[SerializeField] [Tooltip("点名结束执行的事件")]*/
    private UnityEvent EndEvent = new UnityEvent();

    private void Awake()
    {
        if (!ShowNameText || !StartButton || names.Count < 2)
            return;//变量未设置全
        StartButton.onClick.AddListener(() => { StartButton.interactable = false; StartCoroutine("StartDianMing"); });
        EndEvent.AddListener(() => StartButton.interactable = true);
    }

    private IEnumerator StartDianMing()
    {
        while (true)
        {
            yield return new WaitForSecondsRealtime(AddTime);
            ShowNameText.text = names[Random.Range(0, names.Count)];
            if ((RuningTime += Time.deltaTime) >= RunTime)
            {
                AddTime *= 1.05f;
                if (AddTime >= 0.2f)
                {
                    RuningTime = 0f;
                    AddTime = 0.01f;
                    break;
                }
            }
        }
        EndEvent.Invoke();
    }
}

标签:点名,SerializeField,AddTime,private,Unity,StartButton,随机,using,names
来源: https://blog.csdn.net/m0_55907341/article/details/122316253