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);
        }
    }
}
相关推荐
淡海水2 天前
【节点】[EvaluateSimulationAdditionalData节点]原理解析与实际应用
unity·游戏引擎·shadergraph·图形·simulation·evaluate
小贺儿开发2 天前
Unity3D 文物互动大屏
3d·unity·实时互动·udp·socket·网络通信
秦奈2 天前
Unity学习复习随笔(12):网络开发基础
网络·笔记·学习·unity
淡海水3 天前
【节点】[EvaluateRefractionData节点]原理解析与实际应用
unity·游戏引擎·shadergraph·data·图形·evaluate·refraction
淡海水3 天前
【节点】[EvaluateScatteringColor节点]原理解析与实际应用
unity·游戏引擎·shadergraph·color·图形·evaluate·scattering
风痕天际3 天前
Godot扫雷游戏制作记录2——鼠标交互
游戏·游戏引擎·godot
lambda4 天前
游戏开发者的CMU动作数据使用指南:如何将AMC文件转Unity动画
unity·游戏开发·动作捕捉·cmu
淡海水4 天前
【节点】[ComputeVertexPosition节点]原理解析与实际应用
unity·游戏引擎·shadergraph·图形·position·compute·vertex
淡海水5 天前
【节点】[ScleraLimbalRing节点]原理解析与实际应用
unity·游戏引擎·shadergraph·图形·ring·limbal·sclera