图片设置
注意这里的图片类型为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;
}
}
}