[英]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.