在Unity中使用unsafe代码实现0GC的文本打字机效果

近日项目里需要实现一个对话文本的打字机效果,在网上看了一圈,居然一水的都是用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++;
            }
        }
    }
}

具体效果:

性能分析:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值