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);
        }
    }
}
相关推荐
Magnum Lehar14 小时前
3d游戏引擎的Utilities模块实现下
c++·算法·游戏引擎
Flamesky14 小时前
Unity编辑器重新编译代码
unity·重新编译
虾球xz18 小时前
游戏引擎学习第277天:稀疏实体系统
c++·学习·游戏引擎
虾球xz20 小时前
游戏引擎学习第276天:调整身体动画
c++·学习·游戏引擎
虾球xz20 小时前
游戏引擎学习第275天:将旋转和剪切传递给渲染器
c++·学习·游戏引擎
虾球xz1 天前
游戏引擎学习第268天:合并调试链表与分组
c++·学习·链表·游戏引擎
qq_5982117571 天前
Unity.UGUI DrawCall合批笔记
笔记·unity·游戏引擎
南玖yy2 天前
C/C++ 内存管理深度解析:从内存分布到实践应用(malloc和new,free和delete的对比与使用,定位 new )
c语言·开发语言·c++·笔记·后端·游戏引擎·课程设计
Tech Synapse2 天前
Unity ML-Agents实战指南:构建多技能游戏AI训练系统
人工智能·游戏·unity
虾球xz2 天前
游戏引擎学习第272天:显式移动转换
c++·学习·游戏引擎