Skip to content

Commit 52e3b47

Browse files
authored
Create CullingGroupExample.cs
1 parent 31cfac5 commit 52e3b47

File tree

1 file changed

+85
-0
lines changed

1 file changed

+85
-0
lines changed
Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
// gets nearby objects using CullingGroup
2+
// Assign this script to some gameobject, that the distance is measured from
3+
4+
using UnityEngine;
5+
6+
namespace UnityLibrary
7+
{
8+
public class CullingGroupExample : MonoBehaviour
9+
{
10+
// just some dummy prefab to spawn (use default sphere for example)
11+
public GameObject prefab;
12+
13+
// distance to search objects from
14+
public float searchDistance = 3;
15+
16+
int objectCount = 5000;
17+
18+
// collection of objects
19+
Renderer[] objects;
20+
CullingGroup cullGroup;
21+
BoundingSphere[] bounds;
22+
23+
void Start()
24+
{
25+
// create culling group
26+
cullGroup = new CullingGroup();
27+
cullGroup.targetCamera = Camera.main;
28+
29+
// measure distance to our transform
30+
cullGroup.SetDistanceReferencePoint(transform);
31+
32+
// search distance "bands" starts from 0, so index=0 is from 0 to searchDistance
33+
cullGroup.SetBoundingDistances(new float[] { searchDistance, float.PositiveInfinity });
34+
35+
bounds = new BoundingSphere[objectCount];
36+
37+
// spam random objects
38+
objects = new Renderer[objectCount];
39+
for (int i = 0; i < objectCount; i++)
40+
{
41+
var pos = Random.insideUnitCircle * 30;
42+
var go = Instantiate(prefab, pos, Quaternion.identity);
43+
objects[i] = go.GetComponent<Renderer>();
44+
45+
// collect bounds for objects
46+
var b = new BoundingSphere();
47+
b.position = go.transform.position;
48+
49+
// get simple radius..works for our sphere
50+
b.radius = go.GetComponent<MeshFilter>().mesh.bounds.extents.x;
51+
bounds[i] = b;
52+
}
53+
54+
// set bounds that we track
55+
cullGroup.SetBoundingSpheres(bounds);
56+
cullGroup.SetBoundingSphereCount(objects.Length);
57+
58+
// subscribe to event
59+
cullGroup.onStateChanged += StateChanged;
60+
}
61+
62+
// object state has changed in culling group
63+
void StateChanged(CullingGroupEvent e)
64+
{
65+
// if we are in distance band index 0, that is between 0 to searchDistance
66+
if (e.currentDistance == 0)
67+
{
68+
objects[e.index].material.color = Color.green;
69+
}
70+
else // too far, set color to red
71+
{
72+
objects[e.index].material.color = Color.red;
73+
}
74+
}
75+
76+
// cleanup
77+
private void OnDestroy()
78+
{
79+
cullGroup.onStateChanged -= StateChanged;
80+
cullGroup.Dispose();
81+
cullGroup = null;
82+
}
83+
84+
}
85+
}

0 commit comments

Comments
 (0)