unity3d - 将 int 字段作为参数参数传递的问题,但所有其他人都可以完美地工作,这怎么可能?
问题描述
代码的屏幕截图有人可以向我解释一下这个脚本中的一切是如何工作的,除了我作为参数传入的一个简单的 int 计数器吗?但是,如果我直接将 int 计数器字段传递给方法而不是使用/引用。para,它工作得很好,这怎么可能?帮助!
解决方案
默认情况下,您为函数提供的参数会被评估并传递其值(例如,不是int xy
传递,而是int xy
, so的值5
)。
因此,如果您直接更改值,例如。CounterAi -= 1;
您只是在更改您传递的值,而不是基础变量。因此,如果您想在这些情况下使用通过引用传递,则必须使用out
or ref
。
如果您更改传递值的参数,但是它的值将被更改而无需使用ref
or out
。
例子:
public void Example1(int myValue) {
// This won't change the actual variable, just the value of the parameter,
// that has been passed
myValue -= 1;
}
public void Example2(ref int myValue) {
// This will change the actual variable,
// it's changing just the value of the parameter again,
// but we're using pass by reference
myValue -= 1;
}
public void Example3(Transform finishLine) {
// This will change the actual variable,
// because it's changing the data within the object,
// that the parameter value refers to.
finishLine.position = flSpts[Random.Range(0, flSpots.Count)].position;
}
推荐阅读
- excel - 有没有办法从标题中计算具有特定列标准的行中的非空白单元格
- python - 查找树中所有路径总和为 S
- python - 即使前进/后退单帧有效,前进/后退播放按钮也不适用于 tkinter 画布上显示的动画
- c# - 当我得到的价值是 42,000 美元时,我如何比较并断言字符串大于 1000 美元。如何将此字符串转换为整数?
- c - C typedef struct不打印char str
- error-handling - 如何处理 Apollo 错误
- java - 我必须检查数组的元素是否与前一个元素相同(java)
- java - 在运行时动态添加新的 AOP Advisor,表达式来自 Spring Framework 中的 rest 端点
- deployment - 无法部署带有“无效或意外令牌”错误的可靠智能合约
- linux - Yocto - 添加树内核模块