Jump to content
This site uses cookies! Learn More

This site uses cookies!

armedunity.com uses cookies to improve user experience.

By continuing to use this site, you agree to allow us to store cookies on your computer.

  • 0
Sign in to follow this  
UnityGamesRoland

Is it possible that this code would break sometimes?

Question

For my manager scripts (such as MenuManager, GameManager, etc...) I always use the singleton pattern.

Recently I looked into generics and came up with this code:

 

Please login or register to see this code.

 

As you can see, the CreateSingleton() method is called in Awake().

I've done some tests and it turns out that I can access the Instance in an Awake() without any errors. Like this:

 

Please login or register to see this code.

 

Is there a chance that the Test script would try to access InputManager.Instance before it is assigned?

I'm suprised that there were no errors, I always used Awake() for assigning and Start() for accessing members.

 

Edited by UnityGamesRoland

Share this post


Link to post
Share on other sites

3 answers to this question

Recommended Posts

  • 0

It could continue to work, it could not. Idk how unity calls for instancing but my guess is it’s sorted maybe (by name or size or something), where your input manager is created and stored closer to the end of the list to update than your test script. I’m saying it’ll most likely always work as long as input manager is stored after the other script.

 

but like I said, idk how it’s ordered and called

 

p.s. When I write my engines, when a scene instances, it starts it like this (create game object>transform add components in order and called awake as each component is being created). For instance:

 

for(i < scene.objects)

{

go = new instance(scene.objects.go);

for(c < scene.objects.components)

{

Comp = go.addcomponent(...[c]);

}

 

public class component : behaviour

{

public component()

{

Awake();

}

}

 

so it depends on where it’s store in the scene/project file. One can use awake to access something like that as long as it’s created after

Share this post


Link to post
Share on other sites
  • 0

@OcularCash I've tried moving things around but it still worked. 😄

Anyways I'll stick to using Awake() and Start() as I said before just to make sure.

 

Are there any benefits of caching the singleton instance of a class though?

Would this make a difference in performance?

 

Please login or register to see this code.

 

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

×