Skip to content

useUnityUpdate Hook

David edited this page Feb 21, 2023 · 1 revision

About

useUnityUpdate() is a hook that allows you to perform simple operations in the Unity's LateUpdate() life cycle.

When not to use it

  • Performing critical operations
  • Reading input during gameplay or intense scenes
  • Performing heavy operations

So... When can I use it?

If performance isn't a problem, you can use to read simple inputs to perform actions (i.e: "Press enter to continue" scene). Should be noticed, that if you're using the new input system, subscribing to callbacks will be more performant than this method.

Steps to implement the hook

1- Create a file called unity-hooks.tsx

2- Copy the following code:

const update = signal({});

export const useUnityUpdate = (callback: () => void) => {
    return update.subscribe(() => callback());
};

function Update(time) {
    requestAnimationFrame(Update);
    update.value = {};
}
requestAnimationFrame(Update);

How to use it:

export const SplashScreen = () => {

    // Callback once per LateUpdate()
    const unsubscribe = useUnityUpdate(() => {
        if(Input.GetKeyDown(KeyCode.A) {
              // Do something
        }
    });

    // always, always, always (ALWAYS!!!) unsubscribe, else you'll have memory leak / bleed
    useEffect(() => {
        return () => {
            unsubscribe();
        }
    }, []);
}