unity3d - Unity .GetParticles() 高 CPU 峰值
问题描述
我在粒子系统上使用 .GetParticles() 以在粒子超出特定范围时将其销毁。我的脚本在下面,并且缓存了粒子系统变量。我附上了占用 CPU 的详细资料图片,它指向 GetParticles()。我找不到任何文档说明为什么这是一种不好的方法,因为该脚本仅附加到一个游戏对象。
任何见解表示赞赏,谢谢!
private void Update()
{if (Time.time > (delayTimer + 0.02f))
{
delayTimer = Time.time;
transform.position = new Vector3(transform.position.x, Water.transform.position.y - 2f, transform.position.z);
//Gets the change in the waters height and resets it
var waterHeightChange = Mathf.Abs(Water.transform.position.y - waterHeight);
waterHeight = Water.transform.position.y;
//Gets the distance to the top of the water to pop the bubble if surpassed
var DistanceToDestroy = Mathf.Abs((Water.transform.position.y + (Water.transform.localScale.y / 2f) - .15f) - transform.position.y);
//Creates a particle array sized a the emitters maximum particles
//Gets the particles from the emitter system and transfers into array of particles, returns total number of particles
//Only called on occasion (once at start really) to make allocation as minimal as possible
if (pSystemParticles == null || pSystemParticles.Length < pSystem.main.maxParticles)
{
pSystemParticles = new ParticleSystem.Particle[pSystem.main.maxParticles];
}
int numParticlesAlive = pSystem.GetParticles(pSystemParticles);
for (int i = 0; i < numParticlesAlive; i++)
{
//Changes the height accordingly for each particle
newPos.Set(pSystemParticles[i].position.x, pSystemParticles[i].position.y, pSystemParticles[i].position.z + waterHeightChange);
//Grab the 'y' positional height relative to the emitter
var particleHeight = newPos.z;
if (particleHeight >= DistanceToDestroy)
{
//Deletes particle if needed
pSystemParticles[i].remainingLifetime = 0;
}
}
//Sets the particle system from the modified array
pSystem.SetParticles(pSystemParticles, numParticlesAlive);
}
}
解决方案
我不确定你为什么会出现这个尖峰,但这似乎超出了你的控制范围。也许您可以使用碰撞模块,在水线上方放置一个不可见的平面,粒子应该停止的位置,然后设置碰撞模块,使粒子在碰撞时失去其整个生命周期(生命周期损失 = 1)。这样它们在与飞机相撞时应该会消失。可能会更快,因为粒子永远不必进入 C# 世界,而且编写的代码要少得多。
推荐阅读
- javascript - 数据表:加载 ajax 后浏览器冻结
- azure - 使用比较运算符连接事实和维度
- python - 为什么异步函数中的变量返回未定义?
- python - 如何在 Python 中的 SQLAlchemy / Postgres 中实际设置 utf-8 编码
- python - 如何在所有存储在一个大列表中的列表中搜索匹配项
- c# - 如何在最后一次拉取之前获取树(HEAD@{1})
- ios - 在从主线程访问后,不得从后台线程对 > 布局引擎进行修改
- python - 为什么当我删除列表时,IPython 管理内存的方式与 CPython 不同?
- javascript - 如果在选择列表中选择了一个选项,如何禁用另一个选择列表中具有相同值的选项
- tfs - TFS 构建/发布未启动。队列有超过 900 个条目