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·编辑器
死也不注释11 小时前
【第一章编辑器开发基础第二节编辑器布局_3GUI元素和布局大小(3/4)】
unity·编辑器
KhalilRuan1 天前
Unity Demo-3DFarm详解-其二
unity·游戏引擎
死也不注释2 天前
【unity编辑器开发与拓展EditorGUILayoyt和GUILayoyt】
unity·编辑器·游戏引擎
Zillionnn3 天前
Unreal Engine 自动设置图像
游戏引擎·虚幻
3 天前
Unity开发中常用的洗牌算法
java·算法·unity·游戏引擎·游戏开发
马特说3 天前
Unity VR手术模拟系统架构分析与数据流设计
unity·系统架构·vr
心前阳光4 天前
Unity WebGL文本输入
unity·游戏引擎·webgl
天涯过客TYGK4 天前
unity A星寻路
unity·游戏引擎
KhalilRuan4 天前
Unity Demo——3D平台跳跃游戏笔记
笔记·游戏·unity·游戏引擎