[英]C# - Unity - Problem with Parameter passing
I'm trying to extract a lot of code in my program and I encountered a problem.我试图在我的程序中提取大量代码,但遇到了问题。
This is my function to extract a smelting process:这是我的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;
}
My Problem is now that I want to add the output to the material with: material += output
.我的问题是现在我想将 output 添加到材料中:
material += output
。 The Command above shows what these parameter look like.上面的命令显示了这些参数的样子。
So it looks like in this case the material
doesn't get assigned correctly.所以看起来在这种情况下,
material
没有正确分配。
I don't want to go the way if(type = copper){copper += output } else if(type = iron)...
我不想 go
if(type = copper){copper += output } else if(type = iron)...
Is there a workaround for that?有解决方法吗?
Thanks in advance!提前致谢!
if BigDouble
is just like a normal double
, it is a value type , and is therefore being passed by value to your method.如果
BigDouble
就像普通的double
一样,它是一个值类型,因此按值传递给您的方法。 You can add the ref
keyword to pass it by reference:您可以添加
ref
关键字以通过引用传递它:
public IEnumerator Smelting(Button button, Image bar, ref BigDouble material, BigDouble output)
However, iterators cannot have ref arguments, so another workaround might be to pass a delegate to the method who's job it is to increment something但是,迭代器不能有 ref arguments,因此另一种解决方法可能是将委托传递给负责增加某些内容的方法
public IEnumerator Smelting(Button button, Image bar, Action<BigDouble> incrementMaterial, BigDouble output) {
....
incrementMaterial(output); // instead of material += output
....
}
and then the caller:然后是调用者:
StartCoroutine(smeltingCore.Smelting(
smeltCopperOreButton,
smeltCopperOreBar,
amount => saveLoadHandler.data.copperBar += amount,
smeltingHandler.smeltCopperOreOutput));
Of course, at this point you're only passing in output
to use it in the delegate so you can simplify both:当然,此时您只需传入
output
以在委托中使用它,因此您可以简化两者:
public IEnumerator Smelting(Button button, Image bar, Action incrementMaterial) {
....
incrementMaterial();
....
}
and和
StartCoroutine(smeltingCore.Smelting(
smeltCopperOreButton,
smeltCopperOreBar,
() => saveLoadHandler.data.copperBar += smeltingHandler.smeltCopperOreOutput
));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.