c# - 当其他浮动时减少一个浮动的值
问题描述
当 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();
}
}
}
解决方案
它继续减少,因为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;
}
}
推荐阅读
- plot - 如何修复 Plots 中的噪音 [julia]
- c# - 我正在尝试使用存储过程从 SQL SERVER.SSMS 获取 Datetime 属性并尝试分配 dateofopening 变量
- angular - 如何从 observable 中获取正确的数据
- javascript - 在相同的对象数组中加入具有相同键的对象
- javascript - 无法从 GitHub 获取 Excel 电子表格数据到 React JS 应用程序
- sql - 如何在 SQL 中输出 2 个最新用户?
- python - 如何计算 Tensorflow 中不变风险最小化的惩罚?
- python - Python tkinter - 使用嵌套框架时无法定位子框架
- python - 如何根据重新采样到 ohlcv 所需的数据来限制具有历史交易的 df 值?
- php - PHP 处理程序中的表单 $_POST 变量为空