Unity中实现获取InputField选中的文字

一:前言

获取到选中的文字:哈哈


二:实现

UGUI的InputField提供了selectionAnchorPosition和selectionFocusPosition,开始选择时的光标下标和当前光标下标

cs 复制代码
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
using System;

public class GameInputField : InputField
{
    private string m_SelectedText;//当前选中的文本
    public string SelectedText
    {
        get
        {
            return m_SelectedText;
        }
    }
    private int m_StartSelectedIndex;//起始选中的下标
    public int StartSelectedIndex
    {
        get
        {
            return m_StartSelectedIndex;
        }
    }
    private int m_EndSelectedIndex;//结束选中的下标
    public int EndSelectedIndex
    {
        get
        {
            return m_EndSelectedIndex;
        }
    }

    private void Update()
    {
        if (Input.GetMouseButtonDown(0) && EventSystem.current.currentSelectedGameObject == gameObject)
        {
            m_StartSelectedIndex = selectionAnchorPosition;
        }
        if (Input.GetMouseButtonUp(0) && EventSystem.current.currentSelectedGameObject == gameObject)
        {
            m_EndSelectedIndex = selectionFocusPosition;
            if (m_EndSelectedIndex < m_StartSelectedIndex)
            {
                int temp = m_StartSelectedIndex;
                m_StartSelectedIndex = m_EndSelectedIndex;
                m_EndSelectedIndex = temp;
            }
            m_SelectedText = text.Substring(m_StartSelectedIndex, m_EndSelectedIndex - m_StartSelectedIndex);
        }
    }
}
相关推荐
℡枫叶℡9 小时前
Unity - Import Activity Window 资源导入诊断信息窗口
unity·资源导入诊断
TO_ZRG11 小时前
Unity 证书校验
unity·游戏引擎
mxwin13 小时前
Unity Shader 切线空间数据是如何计算出来的
unity·游戏引擎·shader
mxwin16 小时前
Unity Shader 法线贴图跟切线空间有什么关系
unity·游戏引擎·贴图·shader
mxwin16 小时前
Unity Shader 贴图和采样的关系 如何保证贴图清晰
unity·游戏引擎·贴图·shader
心前阳光18 小时前
Unity之使用火山引擎实现文字提问流式回复
unity·游戏引擎·火山引擎
mxwin21 小时前
Unity Shader 什么是球谐光照 原理是什么
unity·游戏引擎·shader
心前阳光21 小时前
Unity之使用火山引擎实现语音识别
unity·语音识别·火山引擎
心前阳光21 小时前
Unity之使用火山引擎实现流式语音合成
unity·游戏引擎·火山引擎