Unity - 确保只有一个实例执行给定的命令

时间:2017-02-02 18:57:34

标签: c# unity3d initialization

我有一些文本要我复制另一个的内容。 为此,我在Start()函数中获取了这些 copycat 文本的所有实例。但是,我只需要这样做一次。为了使这个紧凑,我不希望在我的 Singleton GameManager 中执行此操作,因此我使用static bool在执行此初始化时更改,如下所示:< / p>

 #region Variables
    //using this so that we get the references of the texts only once.
    static bool _initDone = false;
    CopyText[] scripts;
    static Text[] texts;
    #endregion
    void Start()
    {
        #region What to do
        /*
         * Getting all this script's gameobjects, and their texts.
         * note that this scripts is attached only to objects with Text attribute.
         * after that nullifying the CopyText array to save space. 
        */
        #endregion
        if (!_initDone)
        {
            //so only the first one of this instance will do it.
            _initDone = true;
            scripts = Object.FindObjectsOfType<CopyText>();
            for (int i = 0; i < scripts.Length; i++)
            {
                try
                {
                    texts[i] = scripts[i].GetComponent<Text>();
                }
                catch
                {
                    //in case it is put on an object that doesn't have a Text
                    Destroy(scripts[i]);
                }

            }
            scripts = null; 
            //by now we should have our references of all copycat texts.
        }
    }

这个应该工作,但我不知道两个实例是否同时运行,而且它们都会做到这一点。有没有办法确保Start()函数仅在这些模仿文本的一个实例上运行?

1 个答案:

答案 0 :(得分:1)

所有Start方法将按顺序运行,Unity有一个主线程,可以顺序运行所有方法。如果不从手动启动的其他线程修改该变量,则不会有任何问题。

鉴于它是一个静态变量,所有实例都将具有访问权限,并且它只存在一次。我不知道这是一个好的设计方法,但它会起作用。

只是为了订购东西,我会在静态方法中分隔该代码并将其称为InitTexts

相关问题