Unity 使用TextMeshPro是做表情包聊天(文图混排)

很多基础的就不讲了,网上资料比较多。这里有很多大坑,主要是在删除的时候

using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using TMPro;
using System.Collections.Generic;
using System.Linq;

public class ChatController : MonoBehaviour {

    //
    //
    public TMP_InputField TMP_ChatInput;

    public TMP_Text TMP_ChatOutput;

    public Scrollbar ChatScrollbar;

    public Button button1;
    public Button button2;

    void OnEnable()
    {
        TMP_ChatInput.onSubmit.AddListener(AddToChatOutput);
        TMP_ChatInput.onValueChanged.AddListener(delegate {
            SaveValue();
        });
        button1.onClick.AddListener(()=> { Emoji(""); });
        button2.onClick.AddListener(() => { Emoji(""); });
    }

    void OnDisable()
    {
        TMP_ChatInput.onSubmit.RemoveListener(AddToChatOutput); 
    }

    public void Emoji(string str)
    {
        TMP_ChatInput.text += str;
    }


    void AddToChatOutput(string newText)
    {
        //Debug.Log(newText);
        // Clear Input Field
        TMP_ChatInput.text = string.Empty;

        var timeNow = System.DateTime.Now;

        TMP_ChatOutput.text += "[<#FFFF80>" + timeNow.Hour.ToString("d2") + ":" + timeNow.Minute.ToString("d2") + ":" + timeNow.Second.ToString("d2") + "] " + newText + "\n";

        TMP_ChatInput.ActivateInputField();

        // Set the scrollbar to the bottom when next text is submitted.
        ChatScrollbar.value = 0;

    }
    private int len;
    private string currentStr;

    private void SaveValue()
    {
        if (len <= iptChat.text.Length)
        {
            currentStr = iptChat.text;
            Debug.Log("add currentStr   " + currentStr);
        }
        else
        {
            if (currentStr.Length >= 10)
            {
                if (currentStr.Substring(currentStr.Length - 1).Equals(">"))
                {
                    if ((IsNumberic(currentStr.Substring(currentStr.Length - 2, 1)) && currentStr.Substring(currentStr.Length - 10, 8).Equals(" currentStr   " + currentStr);
                    len = currentStr.Length;
                    iptChat.text = currentStr;
                }
                else
                {
                    currentStr = currentStr.Substring(0, currentStr.Length - 1);
                    Debug.Log("delete无> currentStr   " + currentStr);
                    len = currentStr.Length;
                    iptChat.text = currentStr;
                }
            }
        }
        len = iptChat.text.Length;
        currentStr = iptChat.text;
    }

    private bool IsNumberic(string oText)
    {
        try
        {
            int var1 = Convert.ToInt32(oText);
            return true;
        }
        catch
        {
            return false;
        }
    }

}

话不多说,直接上图

111.png

本次水文结束

你可能感兴趣的:(Unity 使用TextMeshPro是做表情包聊天(文图混排))