在Unity C#中使用脚本更改UI图像 [英] Change the UI image using script in unity c#

查看:377
本文介绍了在Unity C#中使用脚本更改UI图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想随机更改 UI图像.我在 UI(canvas)中有一个游戏对象,其中包含 Image组件,并且最初具有 null图像.我有一个附加的脚本(游戏对象)可以在运行时更改图像.

I want to change the UI image in random order. I have a gameobject in UI(canvas) containing Image component and it has null image initially. I have a script attached to it(gameobject) to change the image on run time.

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

public class changeImg : MonoBehaviour {

public Sprite sprite1;
public Sprite sprite2;
public Sprite sprite3;

void Start()
  {
   ChangeImg();
  }
void ChangeImg()
   {
      int rand=Random.Range(0,3);
      if(rand==0)
        {
         gameObject.GetComponent<Image> ().sprite = sprite1;
        //gameObject.GetComponent<UnityEngine.UI.Image> ().sprite = sprite1;
         }
       else if(rand==1)
        {
         gameObject.GetComponent<Image> ().sprite = sprite2;
       // gameObject.GetComponent<UnityEngine.UI.Image> ().sprite = sprite2;
         }
       else if(rand==2)
        {
         gameObject.GetComponent<Image> ().sprite = sprite3;
       //gameObject.GetComponent<UnityEngine.UI.Image> ().sprite = sprite3;
         }
   }
}

我在检查器中分配了公共字段(sprite1,sprite2,sprite3).正如我在代码中评论的那样,我尝试了两种选择.我没有收到错误,但是图像也没有得到我想要的更改. 在程序运行期间,GameObject(脚本附加到该游戏对象)具有空的图像源.

I have assigned the public field (sprite1,sprite2,sprite3) in inspector. And I tried the both option as I had commented in code. I did not get an error but also the image did not get change as I want. During runtime of a program, GameObject(to which the script is attached) has null image source as it was initially.

推荐答案

使用overrideSprite字段代替sprite-不幸的是,统一ui充满了此类陷阱,并且api完全违反直觉,因此您必须小心并定期检查文档

Unfortunately, unity ui is full of such pitfalls and it's api is totally counter-intuitive, so you have to be careful and check the docs regularly

这篇关于在Unity C#中使用脚本更改UI图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆