ThomagicRenderer/Runtime/Scripts/TileObjectRenderer.cs

134 lines
3.3 KiB
C#

using System;
using System.Collections.Generic;
#if UNITY_EDITOR
using UnityEditor;
#endif
using UnityEngine;
using UnityEngine.Rendering;
namespace Assets.ThoMagic.Renderer
{
[ExecuteAlways]
[DisallowMultipleComponent]
public class TileObjectRenderer : MonoBehaviour
{
/// <summary>
/// This event is called after this detail renderer is initialized.
/// </summary>
public event EventHandler<TileObjectRenderer> Initialized;
[NonSerialized]
private bool isInitialized = false;
[Tooltip("Delay the initialization of ThoMagic Renderer until the first LateUpdate event")]
[SerializeField]
private bool _delayInitialize = true;
private bool CanInitialize() => isActiveAndEnabled;
[NonSerialized]
private TileObjectStreamer tileObjectStreamer;
private void Awake()
{
//Load resources
}
private void OnEnable()
{
if (_delayInitialize && Application.isPlaying || (isInitialized || !CanInitialize()))
return;
Initialize();
}
private void Start()
{
if (_delayInitialize && Application.isPlaying || (isInitialized || !CanInitialize()))
return;
Initialize();
}
private void OnDisable()
{
if (!isInitialized)
return;
Destroy();
}
private void OnDestroy()
{
if (!isInitialized)
return;
Destroy();
}
private void Initialize()
{
if (isInitialized)
return;
if (tileObjectStreamer == null)
tileObjectStreamer = new TileObjectStreamer(gameObject);
tileObjectStreamer?.Load();
if (Initialized != null)
Initialized(this, this);
isInitialized = true;
#if UNITY_EDITOR
SceneView.lastActiveSceneView?.Repaint();
RenderPipelineManager.endContextRendering -= OnBeginContextRendering;
RenderPipelineManager.endContextRendering += OnBeginContextRendering;
#endif
}
#if UNITY_EDITOR
private void OnBeginContextRendering(
ScriptableRenderContext context,
List<Camera> cameras)
{
//LateUpdate();
}
#endif
private void LateUpdate()
{
if (!isInitialized && CanInitialize())
Initialize();
if (!isInitialized)
return;
tileObjectStreamer?.LateUpdate();
}
private void Destroy()
{
if (!isInitialized)
return;
try
{
tileObjectStreamer?.Destroy();
}
catch { }
tileObjectStreamer = null;
isInitialized = false;
#if UNITY_EDITOR
RenderPipelineManager.endContextRendering -= OnBeginContextRendering;
#endif
}
private void OnTransformChildrenChanged()
{
tileObjectStreamer?.MarkDirty();
}
}
}