[英]C# - Unity - Problem with Parameter passing
我试图在我的程序中提取大量代码,但遇到了问题。
这是我的function提取冶炼过程:
public IEnumerator Smelting(Button button, Image bar, BigDouble material, BigDouble output)
{
button.interactable = false;
float t = 0f;
while (t <= 1f)
{
bar.fillAmount = t;
t += Time.deltaTime / 4;
yield return null;
}
bar.fillAmount = 0;
//saveLoadHandler.data.copperBar += smeltingHandler.smeltCopperOreOutput;
material += output;
button.interactable = true;
}
我的问题是现在我想将 output 添加到材料中: material += output
。 上面的命令显示了这些参数的样子。
所以看起来在这种情况下, material
没有正确分配。
我不想 go if(type = copper){copper += output } else if(type = iron)...
有解决方法吗?
提前致谢!
如果BigDouble
就像普通的double
一样,它是一个值类型,因此按值传递给您的方法。 您可以添加ref
关键字以通过引用传递它:
public IEnumerator Smelting(Button button, Image bar, ref BigDouble material, BigDouble output)
但是,迭代器不能有 ref arguments,因此另一种解决方法可能是将委托传递给负责增加某些内容的方法
public IEnumerator Smelting(Button button, Image bar, Action<BigDouble> incrementMaterial, BigDouble output) {
....
incrementMaterial(output); // instead of material += output
....
}
然后是调用者:
StartCoroutine(smeltingCore.Smelting(
smeltCopperOreButton,
smeltCopperOreBar,
amount => saveLoadHandler.data.copperBar += amount,
smeltingHandler.smeltCopperOreOutput));
当然,此时您只需传入output
以在委托中使用它,因此您可以简化两者:
public IEnumerator Smelting(Button button, Image bar, Action incrementMaterial) {
....
incrementMaterial();
....
}
和
StartCoroutine(smeltingCore.Smelting(
smeltCopperOreButton,
smeltCopperOreBar,
() => saveLoadHandler.data.copperBar += smeltingHandler.smeltCopperOreOutput
));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.