Change the UI image using script in unity c#

后端 未结 4 527
走了就别回头了
走了就别回头了 2021-01-24 04:58

I want to change the UI image in random order. I have a gameobject in UI(canvas) containing Image component and it has nul

相关标签:
4条回答
  • 2021-01-24 05:30

    Use overrideSprite field instead of sprite - documentation

    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

    0 讨论(0)
  • 2021-01-24 05:33

    To change the Image from a Button, don't use GetComponent<Image> () as you can potentially get another Image component that does not belong to the button. It can also return null if the object is disabled.

    Use the Button.image.sprite or Button.image.overrideSprite variable instead.

    public Button pb;
    public Sprite newSprite;
    
    void Start()
    {
        pb.image.sprite = newSprite; 
    }
    

    Or

    pb.image.overrideSprite = newSprite; 
    

    It really doesn't matter which one is used. Any of these two should work.

    0 讨论(0)
  • 2021-01-24 05:37

    You can also just use Image if you are in Unity 2017.3 (not sure if this works for older versions). For example:

    using UnityEngine.UI;
    -----
    public Image ObjectwithImage;
    public Sprite spriteToChangeItTo;
    
    void Start () {
            ObjectwithImage.sprite = spriteToChangeItTo;
        }
    

    Works great for me.

    0 讨论(0)
  • 2021-01-24 05:42

    Have you checked the position of the Gameobject? Also the color of the image?

    0 讨论(0)
提交回复
热议问题