Skip to content

Instantly share code, notes, and snippets.

@liamcary
Created June 14, 2023 02:15
Show Gist options
  • Save liamcary/e751e3d5fdbc349ddd30b5e1c97cf53d to your computer and use it in GitHub Desktop.
Save liamcary/e751e3d5fdbc349ddd30b5e1c97cf53d to your computer and use it in GitHub Desktop.
A generic, abstract base class for Normcore RealtimeComponents that handles OnRealtimeModelReplaced and calls more self-explanatory methods for common usages.
using Normal.Realtime;
using System;
public abstract class BaseComponentRealtime<TModelRealtime> : RealtimeComponent<TModelRealtime>
where TModelRealtime : RealtimeModel, new()
{
public bool IsOwnershipSupported => model.hasMetaModel;
public bool PreventOwnershipTakeover
{
get => model.preventOwnershipTakeover;
set => model.preventOwnershipTakeover = value;
}
public bool IsInitialized { get; private set; }
public event Action OnInitialized;
protected readonly Serilog.ILogger _logger = new Logger<TModelRealtime>();
protected override void OnRealtimeModelReplaced(TModelRealtime previousModel, TModelRealtime currentModel)
{
if (previousModel != null) {
UnregisterModelEvents(previousModel);
}
if (currentModel != null) {
if (currentModel.isFreshModel) {
InitializeLocalValues(currentModel);
}
RegisterModelEvents(currentModel);
if (!IsInitialized) {
IsInitialized = true;
HandleModelInitialized();
OnInitialized?.Invoke();
}
}
}
/// <summary>
/// This method runs immediately when a Realtime prefab is instantiated locally and only runs on the local client.
/// Use this to set the initial values in a RealtimeModel and remote clients will immediately have these values when
/// the instance is spawned on their side.
/// </summary>
/// <param name="freshModel"></param>
protected virtual void InitializeLocalValues(TModelRealtime freshModel) { }
/// <summary>
/// This method executes once this RealtimeComponent has had it's model data initialized, whether remote or local.
/// Note that other realtime components on this object or in the hierarchy may not be initialized yet.
/// </summary>
protected virtual void HandleModelInitialized() { }
/// <summary>
/// This method executes every time the RealtimeComponent's model is initialized OR replaced. The underlying Models may be
/// replaced at run time so you should register for RealtimeModel events here instead of Start/Awake.
/// </summary>
/// <param name="newModel"></param>
protected virtual void RegisterModelEvents(TModelRealtime newModel) { }
/// <summary>
/// This method executes every time the RealtimeComponent's model is destroyed OR replaced. The underlying Models may be
/// replaced at run time so you should unregister for RealtimeModel events here instead of OnDestroy.
/// </summary>
/// <param name="oldModel"></param>
protected virtual void UnregisterModelEvents(TModelRealtime oldModel) { }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment