Unity框选效果

图片设置

注意这里的图片类型为Sliced

代码如下

using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;

public class BOXSelect_ : MonoBehaviour
{
    Vector2 statrtpos;
    Vector2 endpos;
    RectTransform rectTransform;

    public List<GameObject> list=new List<GameObject>();
    // Start is called before the first frame update
    void Start()
    {
        rectTransform=GetComponent<RectTransform>();

        for (int i = 0; i < 3; i++)
        {
            GameObject g = GameObject.CreatePrimitive(PrimitiveType.Cube);
            g.transform.position = new Vector3(i, 0, 0);
            list.Add(g);
        }
    }

    // Update is called once per frame
    void Update()
    {
        if(Input.GetMouseButtonDown(0))
        {
            //坐标转换
            RectTransformUtility.ScreenPointToLocalPointInRectangle(transform.parent as RectTransform, new Vector2(Input.mousePosition.x, Input.mousePosition.y),null,out statrtpos);

        }

        if (Input.GetMouseButton(0))
        {
            RectTransformUtility.ScreenPointToLocalPointInRectangle(transform.parent as RectTransform, new Vector2(Input.mousePosition.x, Input.mousePosition.y), null, out endpos);
            //开始位置加结束位置/2算出中心点
            Vector3 center=(statrtpos+endpos)/2;
            //结束位置x-开始位置x算出宽
            float w=Mathf.Abs(endpos.x-statrtpos.x);
            //结束位置y-开始位置y算出高
            float h =Mathf.Abs(endpos.y-statrtpos.y);
            //自身位置在中心
            transform.localPosition = center;
            //赋值大小  
            rectTransform.sizeDelta= new Vector2(w, h); 
        }

        if(Input.GetMouseButtonUp(0))
        {
            //鼠标抬起后判断物体是否被选中
            for (int i = 0; i < list.Count; i++)
            {
                //转换坐标
                Vector3 pos = Camera.main.WorldToScreenPoint(list[i].transform.position);
                //判断是否包含物体的位置
                if (RectTransformUtility.RectangleContainsScreenPoint(rectTransform,pos))
                {
                    //选中的物体变色
                    list[i].GetComponent<MeshRenderer>().material.color = Color.red; 
                }
            }

          //  rectTransform.sizeDelta = Vector2.zero;
        }
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值