PortalOptimization.cs
2.71 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
74
75
76
77
78
79
80
81
82
83
84
85
86
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Knife.Portal
{
public class PortalOptimization : MonoBehaviour
{
[SerializeField] private float cullRadius = 3f;
[SerializeField] private PortalView portalView;
[SerializeField] private PortalTransition portalTransition;
[SerializeField] private Camera cullCamera;
[SerializeField] private bool frustumCulling;
private CullingGroup cullingGroup;
private bool isVisible;
private void OnEnable()
{
if (cullCamera == null)
{
Debug.LogWarning("cullCamera is null, so MainCamera (with tag MainCamera) will be used as cullCamera");
cullCamera = Camera.main;
}
cullingGroup = new CullingGroup();
var boundingSpheresArray = new BoundingSphere[1];
boundingSpheresArray[0] = new BoundingSphere(transform.position, cullRadius);
cullingGroup.SetBoundingSpheres(boundingSpheresArray);
cullingGroup.SetBoundingSphereCount(1);
cullingGroup.targetCamera = cullCamera;
cullingGroup.onStateChanged += OnStateChanged;
portalTransition.OnPortalOpen += OnPortalOpen;
portalTransition.OnPortalClose += OnPortalClose;
if(!portalTransition.IsPortalOpened)
portalView.StopRendering();
}
private void OnPortalClose()
{
portalView.StopRendering();
}
private void OnPortalOpen()
{
if(isVisible || !frustumCulling)
portalView.StartRendering();
}
private void OnStateChanged(CullingGroupEvent sphere)
{
if (!frustumCulling)
return;
if (sphere.hasBecomeInvisible)
{
portalView.StopRendering();
isVisible = false;
}
else if (sphere.hasBecomeVisible)
{
if (portalTransition.IsPortalOpened)
{
portalView.StartRendering();
}
isVisible = true;
}
}
private void OnDrawGizmos()
{
Gizmos.color = Color.yellow;
Gizmos.DrawWireSphere(transform.position, cullRadius);
}
private void OnDisable()
{
cullingGroup.onStateChanged -= OnStateChanged;
portalTransition.OnPortalOpen -= OnPortalOpen;
portalTransition.OnPortalOpen -= OnPortalClose;
cullingGroup.Dispose();
}
}
}