Ich habe einige Texte, die ich den Inhalt eines anderen kopieren möchte. Dafür bekomme ich alle Instanzen dieser Nachahmer Texte in der Start()
Funktion. Ich muss dies jedoch nur einmal tun. Um diesen kompakt zu machen, möchte ich nicht, dies zu tun in meinem Singleton GameManager
, so dass ich ein static bool
, die geändert wird, wenn ich diese Initialisierung tun wie so:Unity - sicherstellen, dass nur eine Instanz den angegebenen Befehl ausführt
#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.
}
}
Diese sollte Arbeit, aber ich habe keine Ahnung, ob zwei Instanzen gleichzeitig laufen und beide diese Magie machen. Gibt es eine Möglichkeit, sicherzustellen, dass die Start()
-Funktion nur auf eine Instanz dieser Nachahmungstexte ausgeführt wird?
Also sagst du ich sollte das Zeug in eine 'statische' Methode schreiben, es in einer meiner' Start() 'Funktionen aufrufen das selbe war wie es jetzt ist? – hei
Ja, Ihr Code wird funktionieren, nur um ein wenig aufgeräumter zu sein Ich würde es auf eine statische Methode verschieben und es von 'Start()' aufrufen. – AxelWass
Hat genau das getan und ja, es funktioniert. Danke für Ihre Hilfe. – hei