我使用的是unity 5.5,我遇到了这个问题。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class WhatTheHell : MonoBehaviour
{
    public static int testVal;

    void Awake()
    {
        SetVal(testVal);
        Debug.Log(testVal);
    }

    void SetVal(int val)
    {
        val = 10;
    }
}


调试结果为0插入10。为什么?

最佳答案

在这里,您将testVal定义为static,因此它将在类内的所有方法中可用(您也可以通过类名WhatTheHell.testVal在类外访问它们)。因此,在这种情况下,实际上不需要传递变量。

然后,您将变量testVal作为值传递给SetVal()方法,因此它将仅传递值,而不传递实际变量。这就是为什么更改未反映实际变量的原因。

以下代码将按预期工作:

public static int testVal=0;

void Awake()
{
    Debug.Log(testVal); // print 0
    SetVal();
    Debug.Log(testVal); // print 10
}

void SetVal()
{
    testVal = 10;
}


有关更详细的解释和示例,请查看Ehsan Sajjad的Story of Pass By Value and Pass By Reference in C#

10-02 21:48