Skip to content

Instantly share code, notes, and snippets.

@phosphoer
Last active December 16, 2021 01:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save phosphoer/d6fd40219ff8ad6ecd3012074bd76b87 to your computer and use it in GitHub Desktop.
Save phosphoer/d6fd40219ff8ad6ecd3012074bd76b87 to your computer and use it in GitHub Desktop.
Lazy Updater
using UnityEngine;
using System.Collections.Generic;
public class DestroyComponentsAtY : LazyUpdater<Component>
{
public float YLevel = -100;
private bool _allBelow;
public DestroyComponentsAtY(IReadOnlyList<Component> objects, int updateCount = 1) : base(objects, updateCount)
{
}
protected override void UpdateStart()
{
_allBelow = true;
}
protected override void UpdateEnd()
{
if (_allBelow)
MarkDone();
}
protected override void UpdateInternal(Component instance, IReadOnlyList<Component> instances)
{
if (instance.transform.position.y < YLevel)
GameObject.Destroy(instance.gameObject);
else
_allBelow = false;
}
}
using System.Collections.Generic;
using System.Collections;
public abstract class LazyUpdater<T>
{
public bool IsDone => _isDone;
private int _currentIndex;
private int _updateCount;
private IReadOnlyList<T> _objectsReadonly;
private bool _isDone;
public LazyUpdater(IReadOnlyList<T> objects, int updateCount = 1)
{
_updateCount = updateCount;
_objectsReadonly = objects;
}
public void Update()
{
for (int i = 0; i < _updateCount; ++i)
{
if (_currentIndex < _objectsReadonly.Count)
{
if (_currentIndex == 0)
UpdateStart();
UpdateInternal(_objectsReadonly[_currentIndex], _objectsReadonly);
}
_currentIndex += 1;
if (_currentIndex >= _objectsReadonly.Count && _objectsReadonly.Count > 0)
{
_currentIndex = 0;
UpdateEnd();
}
}
}
public IEnumerator RunAsync()
{
while (!IsDone)
{
Update();
yield return null;
}
}
public void MarkDone()
{
_isDone = true;
}
protected abstract void UpdateStart();
protected abstract void UpdateInternal(T instance, IReadOnlyList<T> instances);
protected abstract void UpdateEnd();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment