首页 > 解决方案 > 将 int 字段作为参数参数传递的问题,但所有其他人都可以完美地工作,这怎么可能?

问题描述

代码的屏幕截图有人可以向我解释一下这个脚本中的一切是如何工作的,除了我作为参数传入的一个简单的 int 计数器吗?但是,如果我直接将 int 计数器字段传递给方法而不是使用/引用。para,它工作得很好,这怎么可能?帮助!

标签: unity3d

解决方案


默认情况下,您为函数提供的参数会被评估并传递其值(例如,不是int xy传递,而是int xy, so的值5)。

因此,如果您直接更改值,例如。CounterAi -= 1;您只是在更改您传递的值,而不是基础变量。因此,如果您想在这些情况下使用通过引用传递,则必须使用outor ref


如果您更改传递值的参数,但是它的值将被更改而无需使用refor 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;
}

推荐阅读