unity 点击事件

目录

点击按钮,显示图片功能教程

第1步添加ui button,添加ui RawImage

第2步 添加脚本:

第3步,把脚本拖拽到button,点击button,设置脚本的变量,

GameObject添加 Component组件


点击按钮,显示图片功能教程

第1步添加ui button,添加ui RawImage

第2步 添加脚本:

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.UI;

public class LoadImageByString : MonoBehaviour
{
    public RawImage showImage;
    public Button loadImage;

    private string imgPath;
    private string imageStr;
    // Start is called before the first frame update

    private void Awake()
    {
        Debug.Log("醒了");
        imgPath = @"C:\Users\Administrator\Pictures\mm\pics\005953_4.jpg";
        Debug.Log(imgPath);

        imageStr = SetImageToString(imgPath);
    }

    void Start()
    {
        Debug.Log("醒了");
        imgPath = @"C:\Users\Administrator\Pictures\mm\pics\005953_4.jpg";
        Debug.Log(imgPath);

        imageStr = SetImageToString(imgPath);
        //  loadImage = gameObject.GetComponent<Button>();
        //  showImage = gameObject.GetComponent<RawImage>();

        Debug.Log("开始");
        // showImage.texture = GetTextureByString(imageStr);
        loadImage.onClick.AddListener(() =>
        {
            showImage.texture = GetTextureByString(imageStr);

        });
    }

    /// <summary>
    /// 将图片转化为字符串
    /// </summary>
    private string SetImageToString(string imgPath)
    {
        Debug.Log("将图片转化为字符串");
        FileStream fs = new FileStream(imgPath, FileMode.Open);
        byte[] imgByte = new byte[fs.Length];
        fs.Read(imgByte, 0, imgByte.Length);
        fs.Close();
        return Convert.ToBase64String(imgByte);
    }

    /// <summary>
    /// 将字符串转换为纹理
    /// </summary>
    private Texture2D GetTextureByString(string textureStr)
    {
        Debug.Log("将字符串转换为纹理");
        Texture2D tex = new Texture2D(10, 10);
        byte[] arr = Convert.FromBase64String(textureStr);
        tex.LoadImage(arr);
        tex.Apply();
        return tex;
    }

    public void onclick()
    {
        Debug.Log("按下了");

    }
}

第3步,把脚本拖拽到button,点击button,设置脚本的变量,

运行,点击button,看RawImage显示图片,至此ok。 

左边选择场景,canvas,选择button,正常情况下,onclick会关联事件函数。

但是从网上开源项目改的,就没有。

GameObject添加 Component组件

  • 9
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AI算法加油站

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值