首页 > 解决方案 > 当其他浮动时减少一个浮动的值

问题描述

当 LevelValue 的值上升时,试图减小 float - timeBtwSpan 的值。

因此,当 LevelValue 更改为 2 时,我触发我的 if 语句以减少 TimebtwSpan,并且它正在发生,但值继续减少无穷大,

这不应该减少一次吗?

根据功能,当 LevelValue == 2 应该发生某些事情..但为什么它继续发生?

public class SPawnHorizontal : MonoBehaviour
{
    public GameObject enemy1;

    Vector2 whereToSpawn;

    public float timeBtwSpan;

    public float decreaseSpawnTime;
    public float minTime = 0.5f;

    private Vector2 screenBounds;

    void Start()
    {
        screenBounds = Camera.main.ScreenToViewportPoint(
            new Vector3(Screen.width, Screen.height, Camera.main.transform.position.z));

        StartCoroutine(decrease());
    }

    public void Update()
    {
        if (TimeLevel.levelValue == 2)
        {
            timeBtwSpan -= decreaseSpawnTime;
        }
    }

    private void spawning()
    {
        GameObject a1 = Instantiate(enemy1) as GameObject;
        a1.transform.position = new Vector2(screenBounds.x * -20, 
        Random.Range(-20, 20)); 
    }

    IEnumerator decrease()
    {
        while (true)
        {
            yield return new WaitForSeconds(timeBtwSpan);
            spawning();
        }
    }
}

标签: c#unity3d

解决方案


它继续减少,因为Update()每帧都会触发。在您的情况下,您可以使用切换:

var _onetime = false;

public void Update()
{
    if (!_onetime && TimeLevel.levelValue == 2)
    {
        timeBtwSpan -= decreaseSpawnTime;
        _onetime = true;
    }
}

// 编辑: 要合并多个级别更改,您必须跟踪以前的级别值并注册值更改。这看起来类似于以下内容(假设您想在 开始减少levelValue >= 2

var _previousLevel = -1;

public void Update()
{
    // added a minimum levelValue of 2 for the trigger
    if(_previousLevel != TimeLevel.levelValue && TimeLevel.levelValue >= 2)
    {
        timeBtwSpan -= decreaseSpawnTime;
        _previousLevel = TimeLevel.levelValue;
    }
}

推荐阅读