Unity3D之日常开发记录

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/Csoap2/article/details/100097516
  • 获取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
    在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/Csoap2/article/details/100097516