Skip to content

Instantly share code, notes, and snippets.

@openroomxyz
Created April 21, 2020 12:12
Show Gist options
  • Save openroomxyz/9635d2172ad87a4c721556fae86683c0 to your computer and use it in GitHub Desktop.
Save openroomxyz/9635d2172ad87a4c721556fae86683c0 to your computer and use it in GitHub Desktop.
Unity : Can i see an example of how to do simple native threaded code?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Threading;
using System;
public class Threadqueuer : MonoBehaviour
{
List<Action> functionsToRunInMainThread;
private void Start()
{
Debug.Log("Started() -- Started");
functionsToRunInMainThread = new List<Action>();
//WHEN WE DEBUG //SlowFunctionThatDoesAUnityThing();
//NO INPUT PARAMETRS //StartThreadedFunction(SlowFunctionThatDoesAUnityThing);
StartThreadedFunction(() => { SlowFunctionThatDoesAUnityThing(Vector3.up, new float[5], new Color[100]); });
Debug.Log("Started() -- Done");
}
private void Update()
{
//Update always runs in the main thread
while(functionsToRunInMainThread.Count > 0)
{
//Grad the first/olderst functions in the list
Action someFunc = functionsToRunInMainThread[0];
functionsToRunInMainThread.RemoveAt(0);
//Now run it
someFunc();
}
}
public void StartThreadedFunction( Action someFunction)
{
Thread t = new Thread(new ThreadStart(someFunction));
t.Start();
}
public void QueueMainThreadFunction(Action someFunction)
{
//We need to make sure that someFunction is running from the
//main thread
functionsToRunInMainThread.Add(someFunction);
}
void SlowFunctionThatDoesAUnityThing( Vector3 foo, float[] bar, Color[] pixels)
{
//First we do a really slow thing
Thread.Sleep(5000); //sleep for 2 seconds
//Now we need to modifie a Unity gameobject
Action aFunction = () =>
{
Debug.Log("The results of the child thread are being applied to the Unity GameObject safely.");
this.transform.position = new Vector3(1, 1, 1); // NOT ALLOWD FROM CHILD THREAD
};
//NOTE: We still arent allowed to call this from child thread
QueueMainThreadFunction(aFunction);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment