我如何在 unity c# 中复制变量?
how can i copy the variable in unity c#?
IEnumerator reload()
{
if (total_bullet >= start_bullet)
{
firable = false;
yield return new WaitForSeconds(reloadtime);
currentbullet = 0 + start_bullet;
total_bullet -= start_bullet;
firable = true;
}
else
{
firable = false;
yield return new WaitForSeconds(reloadtime);
currentbullet = 0 + total_bullet;
total_bullet -= total_bullet;
firable = true;
}
}
}
这是我的游戏的重新加载代码。之后每次射击都会减少当前子弹。
但是重新加载后,有时 total_bullet 反而减少,有时却没有。我想我需要复制变量,但这是正确的解决方案吗?如果是,我该怎么做?
在查看您的代码时,我能找到不减少 total_bullet
的唯一原因是 start_bullet
为零。
这行代码total_bullet -= total_bullet;
使得total_bullet的值等于0,所以可以直接设置变量为0。
IEnumerator reload()
{
firable = false;
if (total_bullet >= start_bullet)
{
yield return new WaitForSeconds(reloadtime);
currentbullet = 0 + start_bullet;
total_bullet -= start_bullet;
firable = true;
}
else
{
yield return new WaitForSeconds(reloadtime);
currentbullet = 0 + total_bullet;
total_bullet = 0;
firable = true;
}
}
一个猜测是;在您开始另一个协程之前,之前的协程可能没有结束,它可能会把事情搞砸。
尝试将协程分配给变量并在再次调用之前停止协程。
类似于:
//Put this at the definitions part of your code.
Coroutine coReload;
//This is for the function where you call your reload() function.
if (coReload != null)
{
StopCoroutine(coReload);
}
coReload = StartCoroutine(reload());
否则,了解更多有关您的代码的信息会很有帮助。
IEnumerator reload()
{
if (total_bullet >= start_bullet)
{
firable = false;
yield return new WaitForSeconds(reloadtime);
currentbullet = 0 + start_bullet;
total_bullet -= start_bullet;
firable = true;
}
else
{
firable = false;
yield return new WaitForSeconds(reloadtime);
currentbullet = 0 + total_bullet;
total_bullet -= total_bullet;
firable = true;
}
}
}
这是我的游戏的重新加载代码。之后每次射击都会减少当前子弹。
但是重新加载后,有时 total_bullet 反而减少,有时却没有。我想我需要复制变量,但这是正确的解决方案吗?如果是,我该怎么做?
在查看您的代码时,我能找到不减少 total_bullet
的唯一原因是 start_bullet
为零。
这行代码total_bullet -= total_bullet;
使得total_bullet的值等于0,所以可以直接设置变量为0。
IEnumerator reload()
{
firable = false;
if (total_bullet >= start_bullet)
{
yield return new WaitForSeconds(reloadtime);
currentbullet = 0 + start_bullet;
total_bullet -= start_bullet;
firable = true;
}
else
{
yield return new WaitForSeconds(reloadtime);
currentbullet = 0 + total_bullet;
total_bullet = 0;
firable = true;
}
}
一个猜测是;在您开始另一个协程之前,之前的协程可能没有结束,它可能会把事情搞砸。
尝试将协程分配给变量并在再次调用之前停止协程。
类似于:
//Put this at the definitions part of your code.
Coroutine coReload;
//This is for the function where you call your reload() function.
if (coReload != null)
{
StopCoroutine(coReload);
}
coReload = StartCoroutine(reload());
否则,了解更多有关您的代码的信息会很有帮助。