When receiving events via socket.On, the callback may run on a background thread. If you need to interact with Unity objects (e.g., transforming a GameObject) or use PlayerPrefs, you must ensure the code runs on the Unity main thread.
Option 1: Using unityThreadScope and OnUnityThread
Set the unityThreadScope property to one of the following: .Update, .LateUpdate, or .FixedUpdate (default is .Update). Then use OnUnityThread instead of On.
Option 2: Using UnityThread.executeIn...
Inside a standard socket.On callback, wrap your Unity-specific logic in UnityThread.executeInUpdate, UnityThread.executeInLateUpdate, or UnityThread.executeInFixedUpdate.
// Option 1: Setting thread scope
socket.unityThreadScope = UnityThreadScope.Update;
socket.OnUnityThread("spin", (response) => {
objectToSpin.transform.Rotate(0, 45, 0);
});
// Option 2: Manual execution in Update
socket.On("spin", (response) => {
UnityThread.executeInUpdate(() => {
objectToSpin.transform.Rotate(0, 45, 0);
});
});