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);
        }
    }
}
相关推荐
Python私教5 小时前
Unity 游戏开发「工业化级」学习路线 2025 版
学习·unity·游戏引擎
于小汐在咯10 小时前
【Unity每日一记】Unity物理引擎:刚体与碰撞体详解
unity·游戏引擎
鱼蛋-Felix14 小时前
Unity jar更新不生效怎么解决
unity·游戏引擎·jar
爱吃小胖橘1 天前
Unity资源加载模块全解析
开发语言·unity·c#·游戏引擎
井队Tell1 天前
打造高清3D虚拟世界|零基础学习Unity HDRP高清渲染管线(第九天)
学习·3d·unity
千年奇葩2 天前
Unity性能优化之:利用CUDA加速Unity实现大规模并行计算。从环境搭建到实战案例
c++·人工智能·unity·游戏引擎·cuda
AA陈超2 天前
虚幻引擎5 GAS开发俯视角RPG游戏 P06-25 属性信息数据资产
c++·游戏·ue5·游戏引擎·虚幻
17岁的勇气2 天前
Unity Shader unity文档学习笔记(二十二):雪地几种实现方式(1. 2D贴花式 2.3D曲面细分并且实现顶点偏移)
笔记·学习·unity·shader
科技快报2 天前
引入实时 3D 渲染技术,地平线与 Unity 开启车载交互空间化时代
3d·unity·交互
爱吃小胖橘2 天前
高效对象池设计:提升Unity性能的关键
开发语言·unity·c#·游戏引擎