-3
\$\begingroup\$

I am using Unity with c#. I have two objects and one needs to call a function from the other which is a Singleton. For this I have two solutions. But what's the best thing to do :
- Call for :
MyScript.Instance.MyFunc();
- Store my Singleton object in my calling object and call it like this :
myScript.MyFunc();

What is the best thing to do in term of performance and optimizations.

Thanks a lot.

\$\endgroup\$
  • 5
    \$\begingroup\$ How often do you call this code per frame? And the big pink elephant in the room: Did you profile? \$\endgroup\$ – Maik Semder Aug 1 '13 at 13:45
  • \$\begingroup\$ This is not called very often, and no profile. My question is general but maybe it's linked with the circumstances. \$\endgroup\$ – MaT Aug 1 '13 at 13:48
  • 5
    \$\begingroup\$ This is an exact duplicate of stackoverflow.com/questions/17995627/… . Please choose one site or the other for asking a question. In this case, this should go on StackOverflow. \$\endgroup\$ – Shotgun Ninja Aug 1 '13 at 14:42
  • \$\begingroup\$ You can see that answers are not the same. And I prefer to have multiple reviews. But thanks for your great answers. \$\endgroup\$ – MaT Aug 2 '13 at 7:35
2
\$\begingroup\$

In Unity things are a bit different, usually this is what I go for when using the singleton design pattern:

  1. Static class (MyClass.Foo();) - Used when creating non-Unity related, static functions. A good example would be a static data manager class that stores information about your player throughout the various scenes.
  2. Mono/Singleton class inheritence (MyClass.Instance.Foo();) - Used when creating a static class that lives in the "Unity lifecycle", for example when you want to use MonoBehaviour's event functions (Update, Awake, etc) or using Unity's coroutines, etc. I've written a short blog post about my custom modified MonoSingletone which can also live through scenes: http://gamedevrant.blogspot.co.il/2013/07/unity-and-singleton-design-pattern.html

Regarding performance, both classes can easily work and get called hundreds of time per frame even on mobile devices - so it's definitely a question of the right tool for your specific problem.

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ You're welcome, good luck! \$\endgroup\$ – Ron Aug 2 '13 at 12:06

Not the answer you're looking for? Browse other questions tagged or ask your own question.