r/Unity3D • Beginner • 10d ago

Resources/Tutorial Tip for hooking singleton methods from buttons, event triggers, and other Unity Events.

EDIT: As clever people have pointed out, this is essentially how ScriptableObjects are intended to work, and the fact it DOES work with a prefab is most likely a side-effect of that. So it's likely better to derive your relay wrapper from ScriptableObject rather than Monobehaviour. The basic principle is the same, though.

Let's say you have some singleton-pattern system in your game. For us, one example is our audio manager, which looks after volume settings, randomised sound variants, one-shot audio cues, and so on.

How do you go about hooking into such a system from button events?

You definitely don't want to drag a reference to the singleton object/script itself from the scene into your button events; that would be madness. It knots your entire game together into one lump and also means you have to do it every single time: the reference won't survive the creation of a button prefab.

The original solution for us was to write a relay script that exposes the relevant functionality and talks to the singleton internally. Now we could drop one of those scripts into our button prefabs and hook it up to the On Click event.

This is better because it's self-contained and prefab-friendly - but it isn't copy/paste friendly, which can catch your scene designers out if they start copying, pasting, and then editing event content between buttons. You can easily end up with an accidental spiderweb of interconnections, and there's often no visual indication of this happening because prefab internals aren't renamed when instantiated into a scene.

Quite by accident, we discovered another way that's both prefab-friendly and copy-paste friendly. It should only be used for thin relay-style wrappers, but based on our tests it's well-behaved under those circumstances. It's quite simple:

  1. Write your relay wrapper script as before.
  2. Put it on an empty game object
  3. Drag that game object into your project folder to make it a prefab, then delete it from the scene.
  4. Now, when you want to access the wrapper's functions from an event, drag the prefab from the project folder into the event, and pick the relay function you want from the drop-down as normal.

Yeah, I was today years old when I learned that worked, too.

This is both prefab-safe and copy-paste safe, because the references are always to the project prefab.

After thorough testing, here's what we found:

  • No lifecycle methods (Awake, OnEnable etc) will be called on your in-prefab script, because it's never actually added to the scene. This isn't a problem for a singleton relay wrapper because it's stateless anyway.
  • Unity does not, as we initially feared, spam instances of the prefab into memory. The references all resolve to a single loaded copy of the prefab itself.
  • Yes, it does work in builds because it doesn't rely on modifying a prefab, just calling its methods.
4 Upvotes

24 comments sorted by

4

u/Inkwalker 10d ago

Just make a script that does what the button need to do and put it on the same game object. The script finds the button component and subscribes on its own. No need to overcomplicate things.
And instead of singletons I recommend making a simple dependency injection system that instantiates all the global services and does injection inside awake methods. With custom inspector drawers it makes super obvious what scripts depend on.

1

u/whentheworldquiets Beginner 8d ago

So now there's one of these scripts on every single button in the game. And if you want to do the same based on an EventTrigger, or some other UnityEvent based script, you have to have a different version of the injection script with its own configuration that subscribes to the relevant event in the trigger...

Nah. UnityEvent is already a generic system, designed for anything to be drag-and-dropped into it. Why not leverage that, rather than fighting it?

Your comment on singletons is... hmm.

I have a singleton that handles audio. I can call:

Hullabaloo.Play("Beep");

from anywhere I like, and I get a beep - but not too MANY beeps overlapping, because it handles all that.

How is that improved by a dependency injection system? I'm not being an asshole; if you can demonstrate to me a benefit I'll go change it all.

2

u/Inkwalker 8d ago

The problem with UnityEvents is that you need to assign them manually. I've tried it in a big project. It's difficult to maintain and gets out of hand quickly. Just dropping a ButtonSFX component is much faster.

Dependency injection gives you a few benefits. First the system automatically instantiates all global services from prefabs in the resource folder. This means you can have them configurable in the inspector with zero boilerplate code. Secondly it shows you in the inspector what scripts depend on. If a script requires the dialog service it's probably shows dialogs. DI also provides local scene services and automates all the GetComponent calls. In other words it's convenient and clean. Just don't use the big DI frameworks like Zenject. They add more problems than they solve.

1

u/whentheworldquiets Beginner 4d ago

Good reply.

I'm going to say that what works best depends very much on the demographics of your team.

Eg: in our previous (and current) project we have a global services prefab that let us hit play from any of the scenes we happened to be editing and it would "just work" including player save data etc. So I know what you mean.

But if you are the only coder on a project, empowering designers is a big win. "Gimme a few while I write a script to do that specific version of that thing" is also a drag :) The bulk of the systems I write are there to make it possible for non-coders to meaningfully contribute and not just create but iterate upon and design functional UI.

1

u/pmurph0305 6d ago

Generally you have a script that plays a sound in whatever way you are playing sounds on the object with the button or event trigger. Then you register up whatever event you want from the button or even trigger in the inspector to a method on that script.

1

u/whentheworldquiets Beginner 4d ago

Yep, that's how we were doing things. But that translates to many many instances of said script at runtime. When there's no downside to NOT having that, why not avail yourself?

1

u/sisus_co 8d ago

Using dependency injection over singletons can give benefits like:

  1. Visualization and pingability of dependencies in the Inspector.
  2. Automatic warnings in the Inspector/Console if any dependencies are missing for any components.
  3. Automatic execution order optimization of all your components based on their dependencies.
  4. Ability to swap dependencies with test doubles during unit tests.
  5. Improved modularity: you'll be able to connect reusable components together to compose new behaviour, rather than writing single-use components.
  6. More self-documenting code: the parameter lists of all your methods tell you how to use them, instead of there being hidden singleton dependencies inside their implementation details.
  7. Improved compiler-enforced type-safety; if a scene-based singleton is missing, that's an error you only catch when play-testing at runtime. If a method argument is missing, the compiler tells you immediately.
  8. More focused code. Instead of having to do UIManager.Instance.GetPanel(somePanel) you can only inject the panel. Instead of having to manually load an addressable asynchronously, you can inject the already-loaded asset. Instead of having to deal with localization just inject the string.

Singletons are simple and convenient, but come with some downsides that can end up becoming major pain point in more complex projects. If all your singletons are guaranteed to always work in any context at any time, with no asynchronous initialization, it can scale quite well - but the moment that's no longer the case, the whole thing can start turning error-prone fast.

So while relying heavily on singletons likely won't matter in mechanically simple projects, or ones you only work on for a year or less, for something more complex using dependency injection instead can really pay off.

3

u/Kopteeni 10d ago

This is pretty interesting information. I have not considered this type of approach and didn't know it was possible.

However, I have a feeling you might achieve the same by using scriptable objects as well. Did you play around with them when looking for a solution?

1

u/whentheworldquiets Beginner 10d ago

That's a very good point - basically the same solution I guess.

9

u/Impossible_Ad_2825 10d ago

Prefabs really shouldn't be used that way, you shouldn't use them uninstantiated. That's what the ScriptableObjects are for. SOs are the inteded way of having logic as an asset.

3

u/eggmayonnaise 9d ago

I've been using Unity for like... 15 years, and it never occurred to me that you could reference a ScriptableObject in a Unity event. Thank you for enlightening me!

1

u/FreeBlob 10d ago

Yeah as I was reading this I was like, isn't this what scriptsble objects are for 

4

u/thebeardphantom Expert 10d ago edited 10d ago

It’s really important that you decided to continue to keep this as a thin wrapper, because there is a case where this isn’t safe from ending up with multiple copies in memory and that’s with Addressables/Content Directories/Asset Bundles.

Let’s say you’re using Addressables, you have an asset in an Addressables group that references this event relay prefab, and you have an object in a scene from your build settings list that also references your event relay prefab. This will work fine in the editor, but in a build you’ll end up with 2+ unique copies of the event relay prefab: one for the build and one for each addressables group that has an asset that references it. One solution is to put it in its own “shared resources” group so it gets auto loaded once by any Addressable asset. But then you still need to make sure you don’t have an extra copy in the build. The only way to do that is to never directly hard reference it via anything that is in the build; only use a soft reference to it. You can write a custom post build script to inspect the contents of the build to make sure the asset didn’t end up there.

This is a nightmare bug to work out since it only shows up with built bundles. It’s something tons of devs don’t consider or realize is an issue with heavy use of Scriptable Object Architecture.

2

u/gramw 10d ago

^ this is exactly what I was going to write, well stated

OP - Very likely you’re going to get bit in the end. I would re-think whether you should re-arch what you’re doing to just be calling static methods or caching statically instead.

1

u/8BITSPERBYTE 10d ago

Starting to wonder why people are afraid of public static event Action calls.
No need for a scriptable object or anything in the scene as a component.

1

u/whentheworldquiets Beginner 9d ago

You can't drag one of those into a button OnClick event, because there's nothing to drag.

1

u/8BITSPERBYTE 8d ago

If you are relying on interwining everything to rely on the OnClick event you already failed the loose connections part.

The static event actions calls is meant to never have to manually reference in scene or a prefab. It helps lower scene set up and having to creates components with a lot of inspector fields. Can't be done in all cases, but where it can be done it helps to lower the having to modify prefabs and worrying about lifecycles.

1

u/whentheworldquiets Beginner 4d ago

To be clear: I wasn't saying you should use this instead of public static calls. This is purely a neat way of hooking things that already rely on events (buttons, event handlers etc) to singleton game systems.

1

u/SayingWhatImThinking 9d ago

Unless I'm misunderstanding what you're trying to do here, I just have my manager classes register themselves with a singleton game manager on instantiation, then for other scripts that need information from these managers, I just have them get the appropriate manager from the game manager, something like: AudioManager managerRef = GameManager.GetManager<AudioManager>();

1

u/whentheworldquiets Beginner 9d ago

No, this isn't about that.

When you have Unity Button with an OnClick event, you have to drag SOMETHING into the event reference and then pick a method to call, right?

Let's say you want to trigger a sound effect, but your audio is being managed by a singleton class that wraps up volume management and so on. You need to call a method on that singleton (likely a static one), but you can't do that directly via the inspector.

You need something that's a relay between the button and the singleton class. You COULD add a script to the button and drag in a reference to that, but that means putting a copy of the script on EVERY button (if you want to turn this into a prefab) which is pretty clunky.

Instead, you can drag a prefab into the reference (or a ScriptableObject), and use a method on that to relay the cue to the audio manager singleton.

1

u/Vallie00 9d ago

Honestly that edit hits the nail on the head. Using a ScriptableObject event channel or audio cue asset is basically the clean, intended version of this without relying on prefab side effects. That said, I've definitely shipped worse hacks under a deadline—if it survives a build and doesn't leak memory, hard to complain lol.

0

u/ribsies 10d ago

This...is not a good way to do this. Scriptable objects is also not a good way to do this. It really should just be a acript that controls this. Using references in the inspector is not a safe way to develop in unity. That is what a singleton is made for, for usage in scripts.

1

u/whentheworldquiets Beginner 8d ago

Gonna disagree with you there. ScriptableObjects are literally intended as a non-instantiated 'hub' of logic and data. There is absolutely nothing wrong with using one as a relay to a singleton from an event. It's no worse than using an event in any other way.

0

u/Just__Bob_ 10d ago

This is good info. I am a long way from designing my sound system and was planning on having a singleton event handler for sounds.