- Home /
Using singleton's methods from everywhere gives wrong results.
I have a class for ColorManagment. And it is attached to some empty gameobject.
public class MyColorManager : MonoBehaviour {
public static MyColorManager instance = null;
private Color myColor = Color.yellow;
private void Awake()
{
if (instance == null)
instance = this;
else if (instance != this)
Destroy(gameObject);
}
void Start () {
myColor = Color.red;
}
public Color GetColor()
{
return myColor;
}
}
And 10 objects in scene which use this script
void Start ()
{
GetComponent<Renderer>().material.color = MyColorManager.instance.GetColor();
}
But the problem is that only the first gameobject's color is red, other 9 gameobjects have yellow colors.
Can't understand what is the problem. Am I using singletons wrong??
Answer by PizzaPie · Jan 21, 2018 at 07:10 PM
Move myColor = Color.red; to Awake() instead of Start() as the execution order of scripts is random, kinda. Or you could manually specify the execution order but I wouldn't recommend it.
What happens is that for the 9 gos their Start() is called, while the color is still set to Yellow (default as you set it), and then ColorManager's Start() is called thus the color changes to Red and lastly the (red GO) has its Start() called.
Cheers!