- 获取UI宽高最安全的方式
RectTransform rect = transform.GetComponent();
rec.rect.width;//宽 - 按钮通过代码添加点击事件并携带参数
使用Lambda表达式

- EventTrigger实现事件调用

- 接口实现拖拽物体
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public class Test : MonoBehaviour,IInitializePotentialDragHandler,IBeginDragHandler,IDragHandler,IEndDragHandler
{
public void OnBeginDrag(PointerEventData eventData)
{
Debug.Log(eventData);
//throw new System.NotImplementedException();
}
public void OnDrag(PointerEventData eventData)
{
var rect = GetComponent<RectTransform>();
Vector3 pos = Vector3.zero;
RectTransformUtility.ScreenPointToWorldPointInRectangle(rect, eventData.position, eventData.enterEventCamera, out pos);
rect.position = pos;
//throw new System.NotImplementedException();
}
public void OnEndDrag(PointerEventData eventData)
{
Debug.Log(eventData);
//throw new System.NotImplementedException();
}
public void OnInitializePotentialDrag(PointerEventData eventData)
{
Debug.Log("开始:"+eventData);
//throw new System.NotImplementedException();
}
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
}
另一种代码实现拖动的方法如下:

通过获取每次拖动变化值实现,但是可能出现在真机上出现拖拽太大,出现拖动失效的问题。
- 接口实现添加物体的点击事件,必须两个物体都定义IPointerClickHandler, IPointerDownHandler的接口

-点击接口获取时间点

- Quaternion四元素的LookRotation方法
使物体一直朝向另一个物体

- 屏幕获取点击物体collider

鼠标控制物体左右旋转
public float speed = 1f;
void OnDrag(Vector2 delta)
{
transform.localRotation = Quaternion.Euler(0f, -0.5f * delta.x * speed, 0f) * transform.localRotation;
}
本文介绍了Unity中实现物体拖拽的多种方法,包括使用EventTrigger和接口实现,以及通过获取拖动变化值来更新物体位置。同时,还探讨了获取UI元素宽高的安全方式,以及如何使用Lambda表达式为按钮添加携带参数的点击事件。
259

被折叠的 条评论
为什么被折叠?



