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

Unity中shotsPerSecond>1时timeBetweenShots为0的问题求助

问题原因与解决方案

核心问题:整数除法的精度丢失

你代码里的timeBetweenShots = 1 / shotsPerSecond;存在整数除法陷阱:1是整数常量,shotsPerSecond也是int类型,C#中整数间的除法会直接舍弃小数部分,只保留整数结果。比如shotsPerSecond=2时,1/2的整数运算结果是0,赋值给float类型变量后就变成0.0f,这就是射速大于1时射击间隔始终为0的原因。

修复后的代码

只需将其中一个操作数转为浮点数,触发浮点除法即可解决:

public class Bullet_Shoot : MonoBehaviour
{
    public GameObject bullet;
    [SerializeField] private float timer;
    public int shotsPerSecond = 1;
    public float timeBetweenShots;

    private void Start()
    {
        timer = 100;
        // 使用1f(浮点常量)替代整数1,执行浮点除法
        timeBetweenShots = 1f / shotsPerSecond;
    }

    void Update()
    {
        timer += Time.deltaTime;

        if(Input.GetButtonDown("Shoot1") && timer >= timeBetweenShots)
        {
            Instantiate(bullet, transform.position, Quaternion.identity);
            timer = 0;
        }
    }
}

射速升级的优化建议

如果你的升级系统需要动态修改shotsPerSecond(比如玩家升级后实时提升射速),可以抽一个方法专门更新射击间隔,避免每次修改都要手动计算:

// 调用此方法更新射速
public void UpdateFireRate(int newRate)
{
    shotsPerSecond = newRate;
    timeBetweenShots = 1f / shotsPerSecond;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 17:01:02