unity 点击事件

目录

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

[第1步添加ui button,添加ui RawImage](#第1步添加ui button,添加ui RawImage)

[第2步 添加脚本:](#第2步 添加脚本:)

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

[GameObject添加 Component组件](#GameObject添加 Component组件)


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

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

第2步 添加脚本:

cs 复制代码
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组件

相关推荐
虾球xz2 小时前
游戏引擎学习第304天:构建与遍历图
c++·学习·算法·游戏引擎
虾球xz2 小时前
游戏引擎学习第300天:从排序键更改为排序规则
c++·学习·算法·游戏引擎
虾球xz4 小时前
游戏引擎学习第305天:在平台层中使用内存 Arena 的方法与思路
c++·学习·游戏引擎
死也不注释4 小时前
【1——Android端添加隐私协议(unity)1/3】
android·unity·游戏引擎
冒泡P4 小时前
Unity Shader入门(更新中)
unity·c#·游戏引擎·图形渲染·着色器
虾球xz1 天前
游戏引擎学习第302天:使用精灵边界进行排序
c++·学习·算法·游戏引擎
虾球xz1 天前
游戏引擎学习第297天:将实体分离到Z层中
c++·人工智能·学习·游戏引擎
Thomas_YXQ1 天前
Unity3D序列化机制详解
java·开发语言·游戏·unity·游戏引擎
虾球xz2 天前
游戏引擎学习第288天:继续完成Brains
c++·学习·游戏引擎
虾球xz2 天前
游戏引擎学习第299天:改进排序键 第二部分
c++·学习·算法·游戏引擎