Unity利用UI框选对象

using System.Collections.Generic;
using UnityEngine;

public class BoxSelect : MonoBehaviour
{
    RectTransform rectTransform;

    Vector3 startpos;

    Rect rect;

    bool IsDrag;

    [SerializeField]
    List<GameObject> list = new List<GameObject>(); // 存储所有游戏对象的列表
    List<GameObject> selectlist = new List<GameObject>(); // 存储所选游戏对象的列表

    void Start()
    {
        rectTransform = transform as RectTransform; // 获取对象的RectTransform组件
    }

    void Update()
    {
        // 检查右键点击以开始选择
        if (Input.GetMouseButtonDown(1))
        {
            startpos = Input.mousePosition; // 存储起始鼠标位置
            IsDrag = true; // 将拖动标志设置为true
        }

        if (IsDrag)
        {
            // 计算选择矩形的宽度和高度
            float w = Mathf.Abs(startpos.x - Input.mousePosition.x);
            float h = Mathf.Abs(startpos.y - Input.mousePosition.y);

            // 设置RectTransform的大小以匹配选择矩形
            rectTransform.sizeDelta = new Vector2(w, h);

            // 计算选择矩形的位置
            float x = startpos.x < Input.mousePosition.x ? startpos.x + w / 2 : Input.mousePosition.x + w / 2;
            float y = startpos.y < Input.mousePosition.y ? startpos.y + h / 2 : Input.mousePosition.y + h / 2;
            rectTransform.anchoredPosition = new Vector2(x - Screen.width / 2, y - Screen.height / 2);

            // 创建一个Rect对象来表示选择矩形
            rect = new Rect(x - w / 2, y - h / 2, w, h);
        }

        // 检查右键释放以结束选择
        if (Input.GetMouseButtonUp(1))
        {
            // 停用列表中游戏对象的所有子对象
            for (int i = 0; i < list.Count; i++)
            {
                list[i].transform.GetChild(0).gameObject.SetActive(false);
            }

            // 遍历列表中的所有游戏对象
            for (int i = 0; i < list.Count; i++)
            {
                // 将游戏对象的世界位置转换为屏幕坐标
                Vector3 pos = Camera.main.WorldToScreenPoint(list[i].transform.position);

                // 检查游戏对象是否在选择矩形内
                if (rect.Contains(pos))
                {
                    selectlist.Add(list[i]); // 将游戏对象添加到所选列表
                    list[i].transform.GetChild(0).gameObject.SetActive(true); // 激活子对象
                }
            }

            startpos = Vector3.zero; // 重置起始位置
            IsDrag = false; // 重置拖动标志
            rectTransform.sizeDelta = Vector2.zero; // 重置选择矩形的大小
        }
    }
}

具体步骤

效果

  • 7
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

抓屁放脚本里

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值