无法访问成员函数中的类变量

时间:2016-07-03 07:05:35

标签: c# oop unity3d

在Unity C#脚本中,我有一个单例游戏控制器对象,其中存储了游戏变量,但在成员函数中访问它时我会遇到奇怪的行为。它打印初始化值,而不是当前值。然而,在更新功能中,它每帧打印正确的值。我总结了下面的课程。控制器类具有对自身的静态引用。如果您需要了解其他详细信息,可以询问。我是C#和Unity的新手,所以我可能缺少一些明显的答案。

由于

public class controller : MonoBehaviour {

    public int[] star = new int[64];

    void Start(){ /* calls another function to set 0 for each star index */ }

    void Update(){  // during gameplay star[0] gets a value of 1
        print(star[0]);  // prints correct value which is 1
    }

    public void checkValue(){
        print(star[0]); // prints 0 incorrectly which should be 1     
    }


}

3 个答案:

答案 0 :(得分:1)

我已经设置了一个小例子。我创建了一个按钮和一个空的游戏对象GameController。我将此代码添加到GameController

using UnityEngine;
using System.Collections;

public class GameController : MonoBehaviour {

    public static GameController instance;

    [System.NonSerialized] public int[] star = new int[64];

    private void Awake()
    {
        if(instance == null)
            instance = this;
        else if(instance != this)
            Destroy(gameObject);

        DontDestroyOnLoad(gameObject);
    }

    private void Start()
    {
        StartCoroutine(SetAllTo(1));
    }

    // for simulating some changes during the game
    private IEnumerator SetAllTo(int value)
    {
        yield return new WaitForSeconds(2.0f);

        for(int i = 0; i < star.Length; i++)
            star[i] = value;

        Debug.Log("Setting done");
    }

    public void PrintFirst()
    {
        Debug.Log(star[0]);
    }
}

现在我向该按钮添加了OnClick个事件,将GameController游戏对象拖入广告位并选择了PrintFirst

我开始游戏并在Coroutine日志之前单击按钮一次,然后在控制台上提供以下内容:

0
Setting Done
1

编辑:
OnClick事件的游戏对象必须在场景中,它不能成为资源文件夹中的预制件。

答案 1 :(得分:0)

在调用ckeckValue

之前,调用启动函数似乎也可能出现在外部调用中

通过在每个函数中添加断点来尝试调试,您​​可以了解正在发生的事情。

答案 2 :(得分:0)

启动功能在游戏开始时运行一次,而不是再次运行。

为此你有模式 - Singleton

为什么要调用外部函数初始化类成员?在你的默认承包商那里做。

- C#默认约束器已在int []中初始化0。

如果你仍然运行什么从代码中的其他范围开始使其公开(c#默认将变量/方法设为私有)