You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity中float转int报错求助:随机数用于Sleep函数问题

问题解决:Unity中float无法转换为int的错误

错误原因

System.Threading.Thread.Sleep()方法要求传入int类型的毫秒数,但你的代码存在类型不匹配问题:

  1. RadNum被声明为float类型
  2. 尽管Random.Range(1000, 20000)返回的是int值,但赋值给float变量后变成了浮点类型,传给Sleep()时触发类型转换错误

两种修复方案

方案1:直接使用int类型变量

将RadNum的类型改为int,全程使用整数类型,彻底避免类型转换问题:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class RandomTimer : MonoBehaviour
{
    public int RadNum = 0;

    void Start()
    {
        RadNum = Random.Range(1000, 20000);
        Debug.Log(RadNum);

        System.Threading.Thread.Sleep(RadNum);
    }
}

方案2:强制类型转换(保留float变量)

如果必须保留RadNum为float类型,将其强制转换为int后再传入Sleep():

// 替换原代码中Sleep的行
System.Threading.Thread.Sleep((int)RadNum);

额外提醒

在Unity中使用Thread.Sleep()会阻塞主线程,导致游戏画面完全卡死。除非你明确需要这种强阻塞效果,否则更推荐使用Unity的协程(Coroutine)实现非阻塞延迟:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class RandomTimer : MonoBehaviour
{
    void Start()
    {
        // 生成1-20秒的随机延迟(对应原代码的1000-20000毫秒)
        float delaySeconds = Random.Range(1f, 20f);
        Debug.Log("延迟时间:" + delaySeconds + "秒");
        StartCoroutine(ExecuteAfterDelay(delaySeconds));
    }

    IEnumerator ExecuteAfterDelay(float delay)
    {
        yield return new WaitForSeconds(delay);
        // 此处编写延迟后需要执行的逻辑
        Debug.Log("延迟完成,开始执行后续操作");
    }
}

内容的提问来源于stack exchange,提问作者McCrazyDude 950

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 00:22:33