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

相关推荐
CreasyChan6 小时前
C# 反射详解
开发语言·前端·windows·unity·c#·游戏开发
IMPYLH9 小时前
Lua 的 Coroutine(协程)模块
开发语言·笔记·后端·中间件·游戏引擎·lua
世洋Blog18 小时前
SiYangUnityEventSystem,一个Unity中的事件系统
观察者模式·unity·c#·游戏引擎·事件系统
呆呆敲代码的小Y18 小时前
【Unity实战篇】| 游戏滑动框添加特殊效果,如实时高亮显示、曲线滑动等
游戏·unity·游戏引擎·实战·u3d·免费游戏·unity实战技巧
Tatalaluola19 小时前
【Quest开发】用unity UI快速实现交互
unity·游戏引擎
技术小甜甜19 小时前
[Godot] 在 Godot 3.1 中配置 ADB 可执行文件的实用指南
游戏·adb·游戏引擎·godot
技术小甜甜20 小时前
【Godot】【入门】Godot 是什么?适合做哪些类型的游戏(附路线图+避坑清单)
游戏·游戏引擎·godot
码界奇点20 小时前
Unity WebGL输入支持终极指南解决浏览器输入难题的完整方案
unity·容器·游戏引擎·鸿蒙系统·webgl
90后小陈老师21 小时前
Unity动画控制
unity·游戏引擎
Miss_SQ1 天前
Webgl打包后删除StreamingAssets文件夹下多余资源
unity·c#·webgl