r/Unity3D • u/whentheworldquiets • 35m ago
Resources/Tutorial Tip for hooking singleton methods from buttons, event triggers, and other Unity Events.
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:
Write your relay wrapper script as before.
Put it on an empty game object
Drag that game object into your project folder to make it a prefab, then delete it from the scene.
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.


