public void CreateTask <T>(ITaskArguments taskArguments, TaskPriority taskPriority = TaskPriority.NORMAL) where T : TaskBehaviour { if (!ReferenceEquals(_currentTask, null) && taskPriority >= _currentTask.TaskPriority) { CancelTask(); TaskBehaviour taskBehaviour = gameObject.AddComponent <T>(); taskBehaviour.Initialize(taskArguments, taskPriority); AddTask(taskBehaviour); return; } // Verify if the new Task is the same as an existing task, if so combine them. if (!ReferenceEquals(_currentTask, null) && _currentTask.TaskArguments.GetTaskType() == taskArguments.GetTaskType()) { _currentTask.Combine(taskArguments); return; } if (_taskBehaviours.Count > 0 && _taskBehaviours.Peek().TaskArguments.GetTaskType() == taskArguments.GetTaskType()) { // It is the same as the next one, therefore don't recreate a task for nothing. _taskBehaviours.Peek().Initialize(taskArguments, taskPriority); } else { TaskBehaviour taskBehaviour = gameObject.AddComponent <T>(); taskBehaviour.Initialize(taskArguments, taskPriority); AddTask(taskBehaviour); } }
private void AddTask(TaskBehaviour taskBehaviour) { _taskBehaviours.Enqueue(taskBehaviour); // Invoke on Add Task event. OnAddTaskEvent?.Invoke(taskBehaviour); if (!_isExecuting) { ScheduleTask(); } }
private void ScheduleTask() { // Task is executing; _isExecuting = true; // Fetch the new task. _currentTask = _taskBehaviours.Dequeue(); // Subscribe to the event. _currentTask.OnEndCallback += OnTaskEnd; // Start executing the task. _currentTask.Execute(); }
private void OnTaskEnd(TaskBehaviour taskBehaviour) { // Unsubscribe to the event. taskBehaviour.OnEndCallback -= OnTaskEnd; Destroy(taskBehaviour); _currentTask = null; // Invoke On End Task Event; OnEndTaskEvent?.Invoke(taskBehaviour); _isExecuting = false; if (_taskBehaviours.Count > 0) { ScheduleTask(); } }