I'm trying to write a system where I can run each enemy's NavMesh pathfinding in parallel, using Job System.
The problem I'm having is that I can't pass the NavMesh agent argument as it's a reference type.
InvalidOperationException: PathfindJob.agent is not a value type. Job structs may not contain any reference types.
I'm probably approaching this problem in a completely wrong way, but this is all I've come up with.
Here's the current Enemy code
using System.ComponentModel;
using Managers;
using Unity.Collections;
using Unity.Jobs;
using UnityEngine;
using UnityEngine.AI;
using UnityEngine.Jobs;
namespace Characters
{
[RequireComponent(typeof(Rigidbody))]
public class Enemy : MonoBehaviour
{
[Header("Stats"), SerializeField] private int _health = 100;
[SerializeField] private int _damage = 20;
[SerializeField] private float _aggroRadius = 10f;
private Rigidbody _body;
private NavMeshAgent _agent;
private Transform _target;
private void Awake()
{
_body = GetComponent<Rigidbody>();
_agent = GetComponent<NavMeshAgent>();
_target = PlayerManager.GetInstance().GetPlayer();
}
private void OnDrawGizmosSelected()
{
Gizmos.color = Color.blue;
Gizmos.DrawWireSphere(transform.position, _aggroRadius);
}
}
public struct PathfindJob : IJobParallelForTransform
{
public Vector3 TargetPosition;
public NavMeshAgent Agent;
public float AggroRadius;
public void Execute(int index, TransformAccess transform)
{
var distance = Vector3.Distance(TargetPosition, transform.position);
if (distance < AggroRadius)
Agent.SetDestination(TargetPosition);
}
}
}
I'm scheduling the job from the GameManager class.