hei
hei

Reputation: 17

Unity - ensure that only one instance does the given command

I have some texts whom I want to copy the content of another one. For this I get all the instances of these copycat texts in the Start() function. However, I need to do this only once. To make this compact, I don't wish to do this in my Singleton GameManager, so I use a static bool that is changed when I do this initialization like so:

 #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.
        }
    }

This should work but I have no notion if two instances will run at the same time and both of them will do this magic. Is there a way to ensure that the Start() function runs only on one instance of these copycat texts?

Upvotes: 0

Views: 596

Answers (1)

AxelWass
AxelWass

Reputation: 1341

All Start methods will run sequentially, Unity has a main thread that runs all the methods sequentially. If you don't modify that variable from an other thread manually started, it won't have any problem.

Given that it is a static variable all instances will have access, and it will only exist once. I don't know if this is a good design approach, but it will work.

Just for ordering stuff I would separate that code in a static method and call it maybe InitTexts.

Upvotes: 1

Related Questions