2

I'm making a unity game, and in my game I have several scripts attached to persistent game objects, when I need to get a value from a different object (such as getting the health from the player object and using it in the UI) I would use ExampleClass exampleClass; exampleClass = FindObjectOfType<ExampleClass> And because there is only ever one of the gameobject this worked fine but I learned about singletons and realized it would make more sense to change to using singletons but now I have run into two different methods of using these singletons.

The first is to create a new object in each class that needs to reference the singleton, like I was doing before but to get the instance from the singleton class and store it in this new object and then reference that object. ExampleClass exampleClass; exampleClass = ExampleClass.Instance

But I have also seen the class directly referenced instead of making a new object. int x; x = ExampleClass.Instance.y This seems to make more sense to me intuitively but I'm not sure if there is a performance reason to make new objects in every class or if its just for conveniences sake.

TLDR: When using singletons in unity is it better to do int x; ExampleClass exampleClass; exampleClass = ExampleClass.Instance; x = exampleClass.y; or should I do int x; x = ExampleClass.Instance.y

Weather Vane
  • 33,872
  • 7
  • 36
  • 56
Killer Kat
  • 35
  • 1
  • 5
  • Before you get too far into this, please read this answer: [you can't have a "singleton" in an ECS system.](https://stackoverflow.com/a/35524924/7392651). For the question: All you get is a reference to the singleton object, if your implementation of the singleton is correct, your `ExampleClass.Instance` returns a reference, not an object. Also keep this in mind [singleton-anti-pattern](https://dzone.com/articles/singleton-anti-pattern) – xcskilab Sep 25 '21 at 18:41

1 Answers1

0

If your singleton is some sort of global service, you can register it in DI container (if you use one). Then use its instance, resolving class examplars (that need to reference the singleton) with DI container.

With regard to choosing between creating object or using the same, in case you register it as singleton and resolve reference in class constructor or DI-property it would work as Flyweight pattern. That is a good practice.