√ Unity3D - 怎么利用代码修改Image组件的图片

1、Image组件显示的图片由SourceImage属性控制,SourceImage属性是Sprite类型的,不是Texture2D类型的,因此需要将Texture2D类型的图片转换成Sprite类型才能赋给SourceImage属性。
2、下面利用一个定时器实现自动切换图片的效果。

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

public class ModifyImage : MonoBehaviour
{
    public Image image;
    public Texture2D texture1;
    public Texture2D texture2;
    public Sprite sprite1;
    public Sprite sprite2;
    public float timer;

    private void Start()
    {
        image = GameObject.Find("Image").GetComponent<Image>();
        texture1 = Resources.Load<Texture2D>("Texture1");
        texture2 = Resources.Load<Texture2D>("Texture2");
        sprite1 = Sprite.Create(texture1, new Rect(0, 0, texture1.width, texture1.height), new Vector2(0.5f, 0.5f));
        sprite2 = Sprite.Create(texture2, new Rect(0, 0, texture2.width, texture2.height), new Vector2(0.5f, 0.5f));
    }

    private void Update()
    {
        timer += Time.deltaTime;
        if (timer < 0.5f)
        {
            image.sprite = sprite1;
        }
        if (timer > 0.5f)
        {
            image.sprite = sprite2;
        }
        if (timer > 1)
        {
            timer = 0;
        }
    }
}

在这里插入图片描述

  • 7
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值