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);
        }
    }
}
相关推荐
AllBlue12 小时前
unity调用安卓方法
android·unity·游戏引擎
郝学胜-神的一滴12 小时前
Horse3D游戏引擎研发笔记(十):在QtOpenGL环境下,视图矩阵与投影矩阵(摄像机)带你正式进入三维世界
c++·3d·unity·游戏引擎·godot·图形渲染·unreal engine
AllBlue15 小时前
unity导出成安卓工程,集成到安卓显示
android·unity·游戏引擎
Sator118 小时前
Unity的FishNet相关知识
网络·unity·游戏引擎
AllBlue18 小时前
安卓调用unity中的方法
android·unity·游戏引擎
李岱诚19 小时前
epic商城下载,ue4报错处理
游戏引擎·ue4
jtymyxmz1 天前
《Unity Shader》10.1.4 折射
unity·游戏引擎
在路上看风景1 天前
12. Burst
unity
平行云PVT2 天前
实时云渲染解决UE5 像素流插件迁移及传输数据受限问题
unity·ue5·xr·实时云渲染·云桌面·像素流·云推流
熬夜敲代码的小N2 天前
Unity WebRequest高级操作:构建高效稳定的网络通信模块
android·数据结构·unity·游戏引擎