Last active
October 16, 2016 23:13
-
-
Save rygo6/72208c2200880c222c7169532d4d4bcf to your computer and use it in GitHub Desktop.
ThreadedGameLogicObject
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using System.Collections; | |
using System.Threading; | |
public class ThreadedGameLogicObject : MonoBehaviour | |
{ | |
private Thread thread; | |
private Transform thisTransform; | |
private Vector3 currentPos; | |
private void Start() | |
{ | |
thisTransform = this.transform; | |
thread = new Thread(ThreadUpdate); | |
thread.Start(); | |
} | |
private void Update() | |
{ | |
thisTransform.position = currentPos; | |
} | |
//Use of FixedUpdate is a simple way to time another tread | |
//In a serious usage of this setup you should make it rely on System.Timers | |
private void FixedUpdate() | |
{ | |
updateThread = true; | |
} | |
private bool runThread = true; | |
private bool updateThread; | |
private void ThreadUpdate() | |
{ | |
while (runThread) | |
{ | |
if (updateThread) | |
{ | |
updateThread = false; | |
currentPos += 1f; //some crazy function that takes forever to do here | |
} | |
} | |
} | |
private void OnApplicationQuit() | |
{ | |
EndThreads(); | |
} | |
//This must be called from OnApplicationQuit AND before the loading of a new level. | |
//Threads spawned from this class must be ended when this class is destroyed in level changes. | |
public void EndThreads() | |
{ | |
runThread = false; | |
//you could use thread.abort() but that has issues on iOS | |
while (thread.IsAlive()) | |
{ | |
//simply have main loop wait till thread ends | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment