So im currently working with making a networking solution for unity using .net sockets and so far its not to hard and ive gotten most of the basic jazz done and I do use threading currently but to use the Unity API in the main thread I had to make a task manager but its not threading so each task is one after another as you would think. So I wondered is there a way to make it thread in some way? I thought of making it so the task manager used coroutines but im not sure how to go about it for some reason and i might have low understanding of how they work.
here are some of my scripts:
Here is the container for the Task Manager that is needed and that makes the task that then goes into the queue of tasks
public class TaskContainer {
static TaskContainer container = null;
public Queue<Task> TaskQueue = new Queue<Task>();
public object _queueLock = new object();
public TaskContainer(){
TaskQueue = new Queue<Task> ();
_queueLock = new object ();
}
public void ScheduleTask(Task newTask){
try{
lock (_queueLock) {
if(TaskQueue.Count < 1000)
{
Debug.Log(TaskQueue.Count);
TaskQueue.Enqueue(newTask);
}
}
}catch(ThreadInterruptedException e){
Debug.Log(e);
}
}
public static TaskContainer GetInstance(){
if (container == null) {
container = new TaskContainer();
}
return container;
}
}
This is the actual tasker that does it
public delegate void Task();
public class TaskManager : MonoBehaviour {
TaskContainer container = null;
void Start()
{
container = TaskContainer.GetInstance ();
}
// Update is called once per frame
void Update () {
if (container != null) {
lock (container._queueLock) {
if (container.TaskQueue.Count > 0) {
container.TaskQueue.Dequeue () ();
}
}
}
}
}
and here is an example of one of the functions that calls those and is needed to be done thread like
TaskContainer container = TaskContainer.GetInstance ();
public void serversinstantiate(string prefabName, string x, string y, string z, string actorId, string clientId)
{
float px = float.Parse (x, CultureInfo.InvariantCulture.NumberFormat);
float py = float.Parse (y, CultureInfo.InvariantCulture.NumberFormat);
float pz = float.Parse (z, CultureInfo.InvariantCulture.NumberFormat);
int id = System.Convert.ToInt32 (actorId);
int cliId = System.Convert.ToInt32 (clientId);
Debug.Log ("Intantiate this: " + prefabName + " at this place: " + px + " " + py + " " + pz);
if (container != null) {
Debug.Log("in if");
container.ScheduleTask (new Task (delegate {
Debug.Log ("in task " + prefabName);
GameObject newObject = (GameObject)GameObject.Instantiate (Resources.Load (prefabName), new Vector3 (px, py, pz), Quaternion.identity);
newObject.GetComponent<AltimitView>().actorId = id;
if(AltimitNetowrk.ClientId == cliId){
newObject.GetComponent<AltimitView>().isMine = true;
}
GetComponent<NetworkManager>().NetowrkObjects.Add(newObject);
}));
}
}