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;
}
}
}