Jump to content

[Solved] Awkward reference to an instance


Recommended Posts

I have one instance of class A, and several instances of class B that have no idea of the existence of class A.

I need to access class A in class B.

Is there a better way/practice to access this class than using something like FindObjectOfType?

Edited by dueb
Link to comment
Share on other sites

If A is a singleton, meaning that there will only be one instance of it ever, you can use the singleton pattern.

class A:

        public static A Instance { get; private set; } = new A();

class B:

        A.Instance.SomeFunction();

 

Link to comment
Share on other sites

1 minute ago, dueb said:

Yes, there will be only one of it ever.

Will investigate that!

Thank you @HebaruSan! :)

You're welcome. I didn't include this before because I wasn't sure singleton was right for you, but you should also make A's constructor private. That way no other classes can make instances, so they have to use the one in your Instance property. Good luck!

Link to comment
Share on other sites

@HebaruSan: So after fiddling around a bit with it, I can confirm you that's exactly what I was searching!

I didn't liked the other method: I don't know why. I had the apprehension like it was not the right one...

So, again: thank you very much! You really helped me there! :wink:

Link to comment
Share on other sites

This thread is quite old. Please consider starting a new thread rather than reviving this one.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...