首页 > 编程语言 > 详细

【Unity】拖动图片生成对应Image

时间:2021-04-30 09:53:51      阅读:26      评论:0      收藏:0      [点我收藏+]

写在前面

  • 拼UI时会用到多个Image,一般操作是:①新建一个Image,②拖入Image用到的图片,③SetNativeSize,④关闭不必要的raycastTarget 。为了能尽快拼完UI,我写了个工具替我完成以上①②③步。因为原先Unity就有拖动图片到对象上自动生成对应Sprite的操作,这个工具覆盖了这个操作,现在拖动图片会生成对应Image,自动SetNativeSize,自动关闭raycastTarget
  • 本工具脚本名为CreateImage.cs,不一定要放在Editor文件夹下。

完整代码

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using UnityEngine.UI;
using Object = UnityEngine.Object;

/// <summary>
/// 从Project窗口拖动图片到Canvas下任意层级,自动生成对应Image
/// 会覆盖原生成Sprite操作
/// </summary>
public class CreateImage
{
    /// <summary>
    /// 总开关
    /// </summary>
    public static bool Switch = true;

    private static bool isTrigger = false;

    [InitializeOnLoadMethod]
    private static void Init()
    {
        if (!Switch)
        {
            return;
        }
        EditorApplication.projectWindowItemOnGUI += ProjectWindowItemOnGui;
        EditorApplication.hierarchyWindowChanged += HierarchyWindowChanged;

    }

    private static void ProjectWindowItemOnGui(string guid, Rect selectionRect)
    {
        if (!Switch)
        {
            return;
        }
        // 拖动图片出Project窗口时
        if (Event.current.type == EventType.DragPerform || Event.current.type == EventType.DragUpdated || Event.current.type == EventType.DragExited)
        {
            isTrigger = true;
        }
       
    }

    private static void HierarchyWindowChanged()
    {
        if (!Switch)
        {
            return;
        }
        if (!isTrigger)
        {
            return;
        }
        // 此时Unity会默认创建Sprite并定位到该GameObject上
        GameObject go = Selection.activeGameObject;
        SpriteRenderer spriteRenderer = go.GetComponent<SpriteRenderer>();
        if (spriteRenderer == null)
        {
            return;
        }
        go.name = "Image";
        RectTransform rt = go.AddComponent<RectTransform>();
        rt.localPosition = Vector3.zero;
        rt.localScale = Vector3.one;
        Image image = go.AddComponent<Image>();
        image.raycastTarget = false;
        image.sprite = spriteRenderer.sprite;
        Object.DestroyImmediate(spriteRenderer);
        image.SetNativeSize();

        isTrigger = false;

    }


}

 

【Unity】拖动图片生成对应Image

原文:https://www.cnblogs.com/caiger-blog/p/14720026.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!