forked from UnityCommunity/UnityLibrary
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCullingGroupExample.cs
93 lines (74 loc) · 2.86 KB
/
CullingGroupExample.cs
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
// gets nearby objects using CullingGroup
// Assign this script to some gameobject, that the distance is measured from
using UnityEngine;
namespace UnityLibrary
{
public class CullingGroupExample : MonoBehaviour
{
// just some dummy prefab to spawn (use default sphere for example)
public GameObject prefab;
// distance to search objects from
public float searchDistance = 3;
public bool colorInvisibleObjects = false;
int objectCount = 5000;
// collection of objects
Renderer[] objects;
CullingGroup cullGroup;
BoundingSphere[] bounds;
void Start()
{
// create culling group
cullGroup = new CullingGroup();
cullGroup.targetCamera = Camera.main;
// measure distance to our transform
cullGroup.SetDistanceReferencePoint(transform);
// search distance "bands" starts from 0, so index=0 is from 0 to searchDistance
cullGroup.SetBoundingDistances(new float[] { searchDistance, float.PositiveInfinity });
bounds = new BoundingSphere[objectCount];
// spam random objects
objects = new Renderer[objectCount];
for (int i = 0; i < objectCount; i++)
{
var pos = Random.insideUnitCircle * 30;
var go = Instantiate(prefab, pos, Quaternion.identity);
objects[i] = go.GetComponent<Renderer>();
// collect bounds for objects
var b = new BoundingSphere();
b.position = go.transform.position;
// get simple radius..works for our sphere
b.radius = go.GetComponent<MeshFilter>().mesh.bounds.extents.x;
bounds[i] = b;
}
// set bounds that we track
cullGroup.SetBoundingSpheres(bounds);
cullGroup.SetBoundingSphereCount(objects.Length);
// subscribe to event
cullGroup.onStateChanged += StateChanged;
}
// object state has changed in culling group
void StateChanged(CullingGroupEvent e)
{
if (colorInvisibleObjects == true && e.isVisible == false)
{
objects[e.index].material.color = Color.gray;
return;
}
// if we are in distance band index 0, that is between 0 to searchDistance
if (e.currentDistance == 0)
{
objects[e.index].material.color = Color.green;
}
else // too far, set color to red
{
objects[e.index].material.color = Color.red;
}
}
// cleanup
private void OnDestroy()
{
cullGroup.onStateChanged -= StateChanged;
cullGroup.Dispose();
cullGroup = null;
}
}
}