Unity3D 如何优化Camera视野外的物体,减少性能消耗

Unity3D 如何优化像机外的物体,减少性能消耗?

在项目中制作场景的过程中,我们经常会使用到大量的粒子系统。比如场景中的火把,在一个村寨中,美术们放置了大量的火把。整个场景中的各个地方,有上百个火把。Unity中,在摄像机范围外的粒子系统虽然不会被绘制。但是update是一直持续的。这也就意味着,这100多个火把,不论是否可见都在更新。这个设计应该是很不合理的,这时就需要一个开关,来控制不可见的粒子系统是否需要update。
有的粒子系统在不可见的时候需要更新,比如爆炸。有的不需要更新,比如火堆火把。

为了避免不必要的update开销,可以写了一个脚本,控制不可见的粒子系统就不更新。
该脚本主要是用到了两个MonoBehaviour的函数。

OnBecameInvisible() 离开相机视野 和 OnBecameVisible() 进入相机视野。

在这里插入图片描述

要这两个函数起作用的前提是,该GameObject必须绑定了MeshRender组件
所以,我们要在粒子系统的GameObject放置在一个GameObject 下,且给该GameObject绑定一个MeshRender 与 MeshFilter。MeshFilter中的mesh可以随便找个cube。

在OnBecameVisible 中 遍历所有child,把active设置为true。
在OnBecameInvisible中 遍历所有child,把active设置为false。

OnBecameVisible():
1)Description
OnBecameVisible is called when the renderer became visible by any camera.
This message is sent to all scripts attached to the renderer. OnBecameVisible and OnBecameInvisible is useful to avoid computations that are only necessary when the object is visible.
2)Example
using UnityEngine;
using System.Collections;public class ExampleClass : MonoBehaviour {
void OnBecameVisible() {
enabled = true;
}
}

OnBecameInvisible():
1)Description
OnBecameInvisible is called when the renderer is no longer visible by any camera.
This message is sent to all scripts attached to the renderer. OnBecameVisible and OnBecameInvisible is useful to avoid computations that are only necessary when the object is visible.
2)Example
using UnityEngine;
using System.Collections;public class ExampleClass : MonoBehaviour {
void OnBecameInvisible() {
enabled = false;
}
}

猜你喜欢

转载自blog.csdn.net/qq_43505432/article/details/117463640
今日推荐