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);
        }
    }
}
相关推荐
死也不注释6 小时前
【Unity UGUI 交互组件——Scrollbar(8)】
unity·游戏引擎·交互
九章云极AladdinEdu15 小时前
绿色算力技术栈:AI集群功耗建模与动态调频系统
人工智能·pytorch·深度学习·unity·游戏引擎·transformer·gpu算力
伽蓝_游戏20 小时前
UGUI源码剖析(15):Slider的运行时逻辑与编辑器实现
游戏·ui·unity·性能优化·c#·游戏引擎·.net
lrh30251 天前
Custom SRP - Complex Maps
unity·srp·render pipeline
m0_497214151 天前
unity中通过拖拽,自定义scroll view中子物体顺序
unity·游戏引擎
地狱为王1 天前
在Unity中实现DTLN-AEC处理音频文件的功能
unity·aec·降噪
SmalBox2 天前
【URP】Shader绘制棋盘格对比内置管线
unity·渲染
郝学胜-神的一滴3 天前
基于OpenGL封装摄像机类:视图矩阵与透视矩阵的实现
c++·qt·线性代数·矩阵·游戏引擎·图形渲染
EQ-雪梨蛋花汤3 天前
【Unity笔记】Unity 编辑器扩展:打造一个可切换 Config.assets 的顶部菜单插件
unity·编辑器·游戏引擎
SmalBox3 天前
【URP】UnityHLSL顶点片元语义详解
unity·渲染