美文网首页
Unity中使用TileMap卡顿的处理

Unity中使用TileMap卡顿的处理

作者: rekcah1986 | 来源:发表于2021-02-24 16:34 被阅读0次

TileMap由格子构成,当格子数过多时,顶点数、面数会特别大,致使真机渲染性能低。
为了解决这个问题,使用了空间换时间的办法:

// 创建RenderTexture
var rt = RenderTexture.GetTemporary(width, height, 16);
rt.filterMode = FilterMode.Point;
// 创建camera
var showCamera = this.transform.CreateChild("ShowCamera").AddComponent<Camera>();
showCamera.orthographic = true;
showCamera.targetTexture = rt;
showCamera.nearClipPlane = -10;
showCamera.cullingMask = 1 << LayerMask.NameToLayer("Ground");
var cameraSize = height / 2.0f / GlobalConfig.PIXELS_PER_UNIT;
showCamera.orthographicSize = cameraSize;
showCamera.transform.localRotation = Quaternion.Euler(90, 0, 0);
yield return null; // 关键:空一帧让camera画一下,我这里用的协程
// 生成Texture2D
var tex2d = new Texture2D(rt.width, rt.height, TextureFormat.RGB24, false);
RenderTexture.active = rt;
tex2d.ReadPixels(new Rect(0, 0, rt.width, rt.height), 0, 0);
tex2d.Apply();
// 释放掉不需要的对象
Destroy(showCamera.gameObject);
RenderTexture.active = null;
RenderTexture.ReleaseTemporary(rt);
// 挂在对象上(自己创建一个)
var render = go.AddComponent<SpriteRenderer>();
var sprite = Sprite.Create(tex2d, new Rect(0, 0, tex2d.width, tex2d.height), Vector2.up);
render.sprite = sprite;
// 把地图上的碰撞框移过来,然后删掉不需要的图层,不写了

第一次用rt,不知道有没有坑,顶点数减少到10%,效果还是很可观的。
对了,有一个警告"Releasing render texture that is set to be RenderTexture.active!"我查了半天没弄明白,最后发现是释放rt前需要调用RenderTexture.active = null.

就这样吧,有用的不对的地方欢迎大家留言。

相关文章

网友评论

      本文标题:Unity中使用TileMap卡顿的处理

      本文链接:https://www.haomeiwen.com/subject/kmmsfltx.html