c# - C# - Unity - 参数传递问题
问题描述
我试图在我的程序中提取大量代码,但遇到了问题。
这是我提取冶炼过程的功能:
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;
}
我现在的问题是我想将输出添加到材料中: material += output
。上面的命令显示了这些参数的样子。
所以看起来在这种情况下material
没有正确分配。
我不想走这条路if(type = copper){copper += output } else if(type = iron)...
有解决方法吗?
提前致谢!
解决方案
ifBigDouble
就像一个 normal double
,它是一个值类型,因此通过值传递给您的方法。您可以添加ref
关键字以通过引用传递它:
public IEnumerator Smelting(Button button, Image bar, ref BigDouble material, BigDouble output)
但是,迭代器不能有 ref 参数,因此另一种解决方法可能是将委托传递给负责增加某些内容的方法
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
));
推荐阅读
- python - 您好,python 3.8.1 的 dedent 空闲是否有问题
- ios - 如何阻止书签崩溃 PDF 应用程序?
- swiftui - SwiftUI 如何在 WKWebView 中添加活动指示器?
- php - 如何在 PHP 中显示数据库中的数据,其中每出现 4 个数据,然后将其他数据放在下面
- r - 如何计算两个数据框中日期范围内的平均值
- f# - F#:在函数声明中指定自定义类型(要配对的复数)
- r - 在 R (dplyr, r) 内分组、占用持续时间和设置条件
- android - 导航抽屉中的多种字体类型 - 导航组件
- javascript - 如何突出显示搜索结果的颜色
- azure - 新文件到达时记录条目的事件中心