forked from Unity-Technologies/EntityComponentSystemSamples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFindNearest.cs
More file actions
73 lines (64 loc) · 2.66 KB
/
Copy pathFindNearest.cs
File metadata and controls
73 lines (64 loc) · 2.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
using Unity.Collections;
using Unity.Jobs;
using Unity.Mathematics;
using UnityEngine;
public class FindNearest : MonoBehaviour
{
// The size of our arrays does not need to vary, so rather than create
// new arrays every field, we'll create the arrays in Awake() and store them
// in these fields.
public NativeArray<float3> TargetPositions;
public NativeArray<float3> SeekerPositions;
public NativeArray<float3> NearestTargetPositions;
public void Awake()
{
Spawner spawner = Object.FindObjectOfType<Spawner>();
// We use the Persistent allocator because these arrays must
// exist for the run of the program.
TargetPositions = new NativeArray<float3>(spawner.NumTargets, Allocator.Persistent);
SeekerPositions = new NativeArray<float3>(spawner.NumSeekers, Allocator.Persistent);
NearestTargetPositions = new NativeArray<float3>(spawner.NumSeekers, Allocator.Persistent);
}
// We are responsible for disposing of our allocations
// when we no longer need them.
public void OnDestroy()
{
TargetPositions.Dispose();
SeekerPositions.Dispose();
NearestTargetPositions.Dispose();
}
public void Update()
{
// Copy every target transform to a NativeArray.
for (int i = 0; i < TargetPositions.Length; i++)
{
// Vector3 is implicitly converted to float3
TargetPositions[i] = Spawner.TargetTransforms[i].localPosition;
}
// Copy every seeker transform to a NativeArray.
for (int i = 0; i < SeekerPositions.Length; i++)
{
// Vector3 is implicitly converted to float3
SeekerPositions[i] = Spawner.SeekerTransforms[i].localPosition;
}
// To schedule a job, we first need to create an instance and populate its fields.
FindNearestJob findJob = new FindNearestJob
{
TargetPositions = TargetPositions,
SeekerPositions = SeekerPositions,
NearestTargetPositions = NearestTargetPositions,
};
// Schedule() puts the job instance on the job queue.
JobHandle findHandle = findJob.Schedule();
// The Complete method will not return until the job represented by
// the handle finishes execution. Effectively, the main thread waits
// here until the job is done.
findHandle.Complete();
// Draw a debug line from each seeker to its nearest target.
for (int i = 0; i < SeekerPositions.Length; i++)
{
// float3 is implicitly converted to Vector3
Debug.DrawLine(SeekerPositions[i], NearestTargetPositions[i]);
}
}
}