将int字段作为参数参数传入的问题,但所有其他字段都能很好地工作,这怎么可能呢



代码截图有人能向我解释一下,除了我作为参数传入的一个简单int计数器之外,这个脚本中的所有东西都是如何工作的吗?但是,如果我直接将int计数器字段传递到方法中,而不是使用/ref。para,它工作得很好,这怎么可能呢?救命!

默认情况下,您给函数的参数会被求值并传递其值(例如,传递的不是int xy,而是int xy的值,所以是5(。

因此,如果你直接更改值,例如CounterAi -= 1;,你只是更改了你传递的值,而不是底层变量。因此,如果要在这些情况下使用按引用传递,则必须使用outref


如果更改传递值的参数,则其值将在不需要使用refout的情况下更改。

示例:

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;
}

最新更新