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组件

相关推荐
ellis197014 小时前
Unity资源管理框架Addressables[六] 内存管理
unity
派葛穆15 小时前
Unity-鼠标悬停改变物体层级
unity·游戏引擎
小贺儿开发18 小时前
Unity3D 爆炸图案例演示
unity·产品·urp·机械拆装·爆炸图·零件·效果设计
Yasin Chen2 天前
Unity TMP_SDF 分析(二)数据来源2
unity·游戏引擎
Mao_Hui2 天前
Unity3d实时读取Modbus RTU数据
开发语言·嵌入式硬件·unity·c#
相信神话20212 天前
《酒魂》游戏开发实战——从设计思想到 Godot 实现(单机完整版)
游戏引擎·godot
心疼你的一切2 天前
【Unity-MCP完全指南:从零开始构建AI游戏开发助手】
人工智能·unity·ai·游戏引擎·aigc·mcp
示申○言舌2 天前
基于知识库(RAG)系统打造由大模型(LLM)驱动NPC游戏的技术设想
游戏·unity·大模型·知识库·rag·智能npc·npc记忆
前端不太难2 天前
OpenClaw 如何运行 Claw 资源文件
c++·开源·游戏引擎
avi91112 天前
UnReal-UE5虚幻蓝图如何修改
ue5·游戏引擎·虚幻·虚幻引擎·ue·蓝图·蓝图逻辑