近日项目里需要实现一个对话文本的打字机效果,在网上看了一圈,居然一水的都是用SubString或者字符串+=拼接实现的,这样虽然方便,但是每次都会产生约30B的内存分配,最终只能自己动手写unsafe代码来实现文本打字机效果了。
demo代码如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
unsafe public class UnsafeTypewriter : MonoBehaviour
{
public Text text;
public string dialogue;
public float delay;
private float timer;
private int index;
private char* strPtr;
void Start()
{
//主动触发新字符串创建 以防修改到原来的字符串
text.text = dialogue + " ";
fixed(char* strPtr = text.text)
{
this.strPtr = strPtr;
//将新字符串置空
for (int i = 0; i < text.text.Length; i++)
{
strPtr[i] = ' ';
}
}
}
void Update()
{
timer += Time.deltaTime;
if (timer >= delay)
{
if (index < dialogue.Length)
{
timer -= delay;
strPtr[index] = dialogue[index];
//主动触发重建来刷新文本显示 手动调用SetAllDirty和Rebuid没用 只能这样了
if ((index & 1) == 0)
{
text.supportRichText = true;
}
else
{
text.supportRichText = false;
}
index++;
}
}
}
}
具体效果:
性能分析: