In continuation of my question about collision caching. I have a script on the manager object with:

private static MyManagerScript instance; public static MyManagerScript Instance { get { if (instance == null) { instance = GameObject.FindObjectOfType<MyManagerScript> (); } return MyManagerScript.instance; } } 

What is the best way to contact this manager in an object? Option 1:

 // напрямую? MyManagerScript.Instance.SomeInt; 

Or option 2:

 private int myInt; // Use this for initialization void Start () { myInt = PauseManagerScript.instance.SomeInt; } // и уже работать с myInt вместо PauseManagerScript.instance.SomeInt // А затем, если нужно, делать PauseManagerScript.instance.SomeInt = myInt 
  • one
    private static for the field may not be enough, try adding a volatile sign if you need all threads to see your instance. - nick_n_a
  • @nick_n_a hmm, and if I have a public int SomeInt { get { return paused; } } public int SomeInt { get { return paused; } } , ie no object can change values ​​in the manager, but only receives them? That is, А затем, если нужно, делать PauseManagerScript.instance.SomeInt = myInt is canceled - Krem Soda
  • one
    Here is a great article about volatile . It is intended for C ++ programmers, but the explanations should be clear. - Lunar Whisper

1 answer 1

If you enter a singleton, then apparently you need it for something. In your example, you can safely use any of the approaches. The difference will begin at the moment when the lifetime of the singleton instance will be less than the lifetime of your behavior. In this case, some objects will work with one instance, and your script - with another.

And here there is a problem related to the fact that you don’t know - what is the limited lifetime of static objects in Unity, and we don’t know whether your manager is an object of the Unity life cycle or not. Read about it yourself or detail the question.

If the manager is the inheritor of Component, then your implementation is incorrect. You must call the DontDestroyOnLoad method for it, otherwise it will be excluded from handling Unity events. Here is an example implementation .

  • That is, if the manager and the object that accesses it are on Scene 1 , and they only exist on this scene (that is, no object that is on another scene is trying to access my manager) is it not at all important to access it directly or cache it? - Krem Soda
  • In the case of correct implementation (by reference above) there will be no difference. In case of an incorrect one, the AppDomain will be unloaded and you will create a new instance of the instance in your singleton and the code will continue to work with different objects. - Lunar Whisper