[solved] Unable to use callbacks in unity?

I’m working on a game completely consisting of sounds in unity, and I want to make use of FMOD’s callback system to identify things like music end, and beat markers, the problem is that I am completely unable to do anything from inside the callback in unity. I’ve done a lot of things to try to work around any thread shenanigans that might be happening; One of it was to simply store that the callback actually happened and doing the hard work later, in a MonoBehaviour’s update

private FMOD.RESULT Stopped(EVENT_CALLBACK_TYPE type, EventInstance eventInstance, IntPtr parameters)
{
try
{
var test = this == null;
_callbackHappened = true;
}
catch (Exception e)
{
var message = e.Message;
}

    return FMOD.RESULT.OK;

}

What is happening is that the test bool is sometimes returning true, and the _callbackHappened assignment throws a nullreference exception…
Could I be wrong or using callbacks on unity isn’t supported?

Callbacks require the use of explicitly pinning memory so that the memory isn’t freed by the garbage collector.

We have an example on our website of how to use callbacks:
https://fmod.com/resources/documentation-api?page=content/generated/engine_new_unity/script_example_timeline.html#/

1 Like

Why are callbacks so tedious? The function headers and extra library calls going on here are quite dizzying. Are there any pitfalls to lookout for when making callbacks a commonplace in our games?

2 Likes

That really did the trick! It sure wasn’t as painless as I want it t be, but after encapsulating all that dizzy stuff it became really simple to work with.
Thanks for the quick response.

@Tanner The extra work is required when interfacing with native code (C, C++, Objective-C, etc.). https://docs.unity3d.com/Manual/NativePlugins.html

As Rafael mentioned, the hard part is the initial setup.

@Cameron - I got it working in my game as well this evening. I actually am attaching and removing the callbacks to/from my event in real-time as the game plays out. There doesn’t seem to be an option to delete a callback from an event once you attach it, so I am just swapping it out for an empty callback before I free the original data object the callback was writing to.

Only one problem though is that destroying the object as mentioned on the example while an event is playing freezes my unity editor

I believe the fix for that will be the same as posted here:

It is due to the GCHandle being freed before the callback is actually finished with it.