Change the UI image using script in unity c#

后端 未结 4 529
走了就别回头了
走了就别回头了 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:33

    To change the Image from a Button, don't use GetComponent () 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.

提交回复
热议问题