Unity的UGUI获取InputField输入框文字当前的 行数——效果展示(图文详情+源码)

本文介绍如何在Unity的UGUI中获取InputField输入框的光标行数。通过自定义InputTest组件替换原有的InputField,并重写OnPointerDown方法,结合TextGenerator计算点击位置对应的行数。源码中提供了GetUnclampedCharacterLineFromPositions函数用于获取当前行数。最终实现了在鼠标点击时输出行数的效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Unity的UGUI获取InputField输入框文字当前的 行数——(图文详情+源码)


🔥需求

UGUI,要获取输入框(InputField)的光标在第几行


🔥效果

废话不多说,先来看下效果
请添加图片描述


🔥设置

需要把原来的InputField组件删除掉,换成InputTest挂载上去,
在这里插入图片描述
这几个位置需要重新指定下


🔥源码

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class InputTest : InputField
{
    
    public override void OnPointerDown(PointerEventData eventData)
    {
        base.OnPointerDown(eventData);
        Vector2 localMousePos;
        RectTransformUtility.ScreenPointToLocalPointInRectangle(textComponent.rectTransform, eventData.pointerPressRaycast.screenPosition, eventData.pressEventCamera, out localMousePos);
        Debug.Log("鼠标点击当前的行数:"+GetUnclampedCharacterLineFromPositions(localMousePos,m_TextComponent.cachedTextGenerator));
    }
   /// <summary>
   /// 返回当前行数
   /// </summary>
   /// <param name="pos"></param>
   /// <param name="generator"></param>
   /// <returns></returns>
    private int GetUnclampedCharacterLineFromPositions(Vector2 pos, TextGenerator generator)
    {
        if (!multiLine)
            return 0;
        float y = pos.y * m_TextComponent.pixelsPerUnit;
        float lastBottomY = 0.0f;

        for (int i = 0; i < generator.lineCount; ++i)
        {
            float topY = generator.lines[i].topY;
            float bottomY = topY - generator.lines[i].height;

            // pos is somewhere in the leading above this line
            if (y > topY)
            {
                // determine which line we're closer to
                float leading = topY - lastBottomY;
                if (y > topY - 0.5f * leading)
                    return i - 1;
                else
                    return i;
            }

            if (y > bottomY)
                return i;

            lastBottomY = bottomY;
        }

        // Position is after last line.
        return generator.lineCount;
    }
}


总结

欢迎大佬多多来给萌新指正,欢迎大家来共同探讨。
如果各位看官觉得文章有点点帮助,跪求各位给点个“一键三连”,谢啦~

声明:本博文章若非特殊注明皆为原创原文链接
https://blog.youkuaiyun.com/Wrinkle2017/article/details/121681714
————————————————————————————————

💢💢版权声明

版权声明:本博客为非营利性个人原创
所刊登的所有作品的著作权均为本人所拥有
本人保留所有法定权利,违者必究!
对于需要复制、转载、链接和传播博客文章或内容的
请及时和本博主进行联系
对于经本博主明确授权和许可使用文章及内容的
使用时请注明文章或内容出处并注明网址
转载请附上原文出处链接及本声明

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值