Use the KNN library for K-Nearest Neighbour queries
mainThe com.akb.knn library provides a high-performance K-Nearest Neighbour (KNN) implementation for Unity using the DOTS technology stack (Burst compiler and Unity Job System). It utilizes K-D trees to accelerate spatial queries and is designed to be allocation-free and multi-threaded.
Core Workflow
- Prepare Data: Create a
NativeArray<float3>containing your point cloud. - Initialize Container: Create a
KnnContainerusing your points. You can choose whether to build the tree immediately via the second constructor argument. - Rebuild (if needed): If the point cloud changes, use
KnnRebuildJobto update the container. - Query: Use specific jobs to perform queries (single point, batch points, or range-based queries) to leverage Burst acceleration and multi-threading.
// Example setup
var points = new NativeArray<float3>(100000, Allocator.Persistent);
// ... fill points ...
// Create container (false = don't build immediately)
var knnContainer = new KnnContainer(points, false, Allocator.TempJob);
// Rebuild the tree
var rebuildJob = new KnnRebuildJob(knnContainer);
rebuildJob.Schedule().Complete();