Skip to content

Instantly share code, notes, and snippets.

@vrobel
Last active December 14, 2021 22:14
Show Gist options
  • Save vrobel/75987bf8477597d1eec137cfe0ff29d2 to your computer and use it in GitHub Desktop.
Save vrobel/75987bf8477597d1eec137cfe0ff29d2 to your computer and use it in GitHub Desktop.
Add context menu to RealtimeView component of Normcore. It allows to clean up Deprecated View references. Deprecated View references can cause issues with Unity's bug in serialization OnAfterDeserialize causing InvalidOperationException: EnsureRunningOnMainThread.
using Normal.Realtime;
using UnityEditor;
using UnityEngine;
namespace Normcore.Editor
{
public static class AddCleanupForRealtimeView
{
[MenuItem("CONTEXT/RealtimeView/Cleanup child views")]
static void RealtimeViewCleanupChildViews(MenuCommand command)
{
ResetRealtimeViewChildViews(command.context);
}
[MenuItem("CONTEXT/RealtimeView/Cleanup ALL child views")]
static void RealtimeViewCleanupAllChildViews(MenuCommand command)
{
var realtimeViews = Object.FindObjectsOfType<RealtimeView>();
foreach (var realtimeView in realtimeViews)
{
ResetRealtimeViewChildViews(realtimeView);
}
}
private static void ResetRealtimeViewChildViews(Object context)
{
var serializedObject = new SerializedObject(context, context);
var propertyPath = "_childViews";
var relativePropertyPath = "view";
var serializedProperty = serializedObject.FindProperty(propertyPath);
if (serializedProperty != null)
{
var serializedPropertyArraySize = serializedProperty.arraySize;
for (int i = serializedPropertyArraySize - 1; i >= 0; i--)
{
var arrayElementAtIndex = serializedProperty.GetArrayElementAtIndex(i);
var viewProperty = arrayElementAtIndex.FindPropertyRelative(relativePropertyPath);
if (viewProperty.objectReferenceValue == null)
{
serializedProperty.DeleteArrayElementAtIndex(i);
}
}
serializedObject.ApplyModifiedProperties();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment