Unity填坑-CullingGroup的运用

Unity填坑-CullingGroup的运用

可以使用CullingGroup动态剔除一些对性能有极大影响的脚本、及渲染的进行。


提示:写完文章后,目录可以自动生成,如何生成可参考右边的帮助文档


前言

CullingGroup可以提供对场景中对象的距离追踪,并提供回调效果。


二、示例代码如下

public class CullingGroupTest : MonoBehaviour
{
    public List<GameObject> Targets;

    public CullingGroup group;

    public BoundingSphere[] spheres;

    public GameObject Player;

    // Start is called before the first frame update
    void Start()
    {
        group = new CullingGroup();
        group.targetCamera = Camera.main;

        group.SetDistanceReferencePoint(Player.transform);

        float[] distances = new float[5];

        for (int i = 0; i < 5; i++)
        {
            distances[i] = 5f*i;
        }

        group.SetBoundingDistances(distances);

        spheres = new BoundingSphere[Targets.Count];

        for (int i = 0; i < Targets.Count; i++)
        {
            spheres[i] = new BoundingSphere(Targets[i].transform.position, 1f);
        }

        group.SetBoundingSpheres(spheres);
        group.SetBoundingSphereCount(Targets.Count);

        group.onStateChanged = StateChangedMethod;
    }

    // Update is called once per frame
    void Update()
    {
        for (int i = 0; i < Targets.Count; i++)
        {
            spheres[i].position = Targets[i].transform.position;
        }
    }

    private void OnDestroy()
    {
        group.Dispose();
    }


    private void StateChangedMethod(CullingGroupEvent evt)
    {
        if (evt.hasBecomeVisible)
        {
            Debug.LogFormat("Sphere {0} has become visible!", evt.index);
            Targets[evt.index].SetActive(true);
        }

        if (evt.hasBecomeInvisible)
        {
            Debug.LogFormat("Sphere {0} has become invisible!", evt.index);
            Targets[evt.index].SetActive(false);
        }
        
        Debug.LogFormat("Sphere {0} has become Change!", evt.index);
    }
}

使用起来很简单,如果只想对这些物体针对摄像机的可见性进行回调,那么去掉group.SetDistanceReferencePoint(Player.transform);以及group.SetBoundingDistances(distances);这两行代码即可。
效果就是:当追踪的物体(通过球体中心与半径判定是否在摄像机视野内)不在摄像机视角内时,触发回调。

如果想设定一个对摄像机的距离范围来进行回调,group.SetBoundingDistances(distances);保留这行代码即可达成目标,可以设置不同的范围区域来进行不同处理。

如果想要让这些追踪物体对另外一个目标进行追踪,则可以保留group.SetDistanceReferencePoint(Player.transform)代码(可以设置trasform,会自动实时改变位置,也可以传入Vector3的定点)。这样可以针对距离这个目标进行回调。


总结

当然完全可以使用自己的方法,去每帧进行距离计算,也可以到达相同的效果。不过利用CullingGroup,进行摄像机的裁减回调还是挺好用的。比如有些纯表现的场景物体,直接SetVisable为false,可以提升不少性能。

  • 9
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值