Skip to content

Instantly share code, notes, and snippets.

@m-rogalski90
Last active December 9, 2018 14:29
Show Gist options
  • Save m-rogalski90/33753fe421250d36ff524605763e076e to your computer and use it in GitHub Desktop.
Save m-rogalski90/33753fe421250d36ff524605763e076e to your computer and use it in GitHub Desktop.
Bunch of scripts for the Unity to help with the development process
public sealed class UnityThread
: MonoBehaviour
{
#if DEBUG
[SerializeField]
#endif
private List<UnityThreadAction> m_Actions = new List<UnityThreadAction>();
void Start()
{
m_Actions = new List<UnityThreadAction>();
}
public void RequestExecution(UnityThreadAction action)
{
#if DEBUG
Debug.Log("trying to add action");
#endif
lock (m_Actions)
{
m_Actions.Add(action);
#if DEBUG
Debug.Log("add action");
#endif
}
}
private List<UnityThreadAction> Dequeue(UnityThreadExecutionType executionType)
{
List<UnityThreadAction> copiedActions = new List<UnityThreadAction>();
lock (m_Actions)
{
for (int i = 0; i < m_Actions.Count; i++)
{
UnityThreadAction action = m_Actions[i];
if (action.ExecutionType == executionType)
{
copiedActions.Add(action);
m_Actions.RemoveAt(i);
--i;
}
}
}
return copiedActions;
}
private void Update()
{
List<UnityThreadAction> copiedActions = Dequeue(UnityThreadExecutionType.EXECUTE_IN_UPDATE);
for (int i = 0; i < copiedActions.Count; i++)
{
copiedActions[i].Action();
}
}
private void LateUpdate()
{
List<UnityThreadAction> copiedActions = Dequeue(UnityThreadExecutionType.EXECUTE_IN_LATE_UPDATE);
for (int i = 0; i < copiedActions.Count; i++)
{
copiedActions[i].Action();
}
}
private void FixedUpdate()
{
List<UnityThreadAction> copiedActions = Dequeue(UnityThreadExecutionType.EXECUTE_IN_FIXED_UPDATE);
for (int i = 0; i < copiedActions.Count; i++)
{
copiedActions[i].Action();
}
}
}
[Serializable]
public class UnityThreadAction
{
public readonly Action Action;
public readonly UnityThreadExecutionType ExecutionType;
public UnityThreadAction(Action action, UnityThreadExecutionType executionType)
{
Action = action;
ExecutionType = executionType;
}
}
[Serializable]
public enum UnityThreadExecutionType
{
EXECUTE_IN_UPDATE,
EXECUTE_IN_LATE_UPDATE,
EXECUTE_IN_FIXED_UPDATE
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment