コガネブログ

平日更新を目標に Unity や C#、Visual Studio、ReSharper などのゲーム開発アレコレを書いていきます

【Unity】string.Format や StringBuilder、TextMesh Pro の割り当てを削減できる「ZString」紹介

はじめに

「ZString」を Uniy プロジェクトに導入することで
string.Format や StringBuilder、TextMesh Pro の割り当てを削減できるようになります

string.Format

通常

using UnityEngine;

public class Example : MonoBehaviour
{
    private void Update()
    {
        var str = string.Format( "{0} / {1}", 25, 100 );
    }
}

f:id:baba_s:20200205113601p:plain

ZString

using Cysharp.Text;
using UnityEngine;

public class Example : MonoBehaviour
{
    private void Update()
    {
        var str = ZString.Format( "{0} / {1}", 25, 100 );
    }
}

f:id:baba_s:20200205113607p:plain

StringBuilder

通常

using System.Text;
using UnityEngine;

public class Example : MonoBehaviour
{
    private void Update()
    {
        var sb = new StringBuilder();

        sb.AppendLine( "ピカチュウ" );
        sb.AppendLine( 25 );
        sb.AppendFormat( "{0} / {1}", 23, 34 );

        var str = sb.ToString();
    }
}

f:id:baba_s:20200205113614p:plain

ZString

using Cysharp.Text;
using UnityEngine;

public class Example : MonoBehaviour
{
    private void Update()
    {
        using ( var sb = ZString.CreateStringBuilder() )
        {
            sb.AppendLine( "ピカチュウ" );
            sb.AppendLine( 25 );
            sb.AppendFormat( "{0} / {1}", 23, 34 );

            var str = sb.ToString();
        }
    }
}

f:id:baba_s:20200205113619p:plain

TextMesh Pro

通常

using TMPro;
using UnityEngine;

public class Example : MonoBehaviour
{
    public TMP_Text m_text;

    private void Update()
    {
        m_text.text = string.Format( "{0} + {1} + {2} = {3}", 1, 2, 3, 6 );
    }
}

f:id:baba_s:20200205113624p:plain

ZString

using Cysharp.Text;
using TMPro;
using UnityEngine;

public class Example : MonoBehaviour
{
    public TMP_Text m_text;

    private void Update()
    {
        m_text.SetTextFormat( "{0} + {1} + {2} = {3}", 1, 2, 3, 6 );
    }
}

f:id:baba_s:20200205113628p:plain