简体   繁体   中英

How to change canvas image via script

I have a script, which change texture of the object (like a plane on the TV) fixed times per second:

public Texture[] frames;                // array of textures
public float framesPerSecond = 2.0f;    // delay between frames

void Update()
{
    int index = (int)(Time.time * framesPerSecond) % frames.Length;
    GetComponent<Renderer>().material.mainTexture = frames[index];
}

With this script I can change texture of plane, quad, etc. But I need to change it for canvas image. I can't change "Image" script. Should I access value "Source Image" of this script? Would it be correct?

And is so, how can I access Image component? I can't write this:

Image image = GetComponent<Image>();

在此处输入图片说明

If you use Image , you need to convert Texture to Sprite then change image.sprite property

Method 1 ( Image )

public Texture[] frames;                // array of textures
public float framesPerSecond = 2.0f;    // delay between frames
Image image = null;

void Start()
{
    //Get Image Reference
    image = gameObject.GetComponent<Image>();
}

void Update()
{
        int index = (int)(Time.time * framesPerSecond) % frames.Length;

        //Convert Texture to Sprite
        Sprite s = Sprite.Create((Texture2D)frames[index], new Rect(0, 0, frames[index].width, frames[index].height),
                                Vector2.zero, 0);
        image.sprite = s; //Change The Image
}

Method 2 ( RawImage ) image.texture If you use RawImage , you just need to change the image.texture property.

public Texture[] frames;                // array of textures
public float framesPerSecond = 2.0f;    // delay between frames
RawImage image = null; 

void Start()
{
 //Get Raw Image Reference
 image = gameObject.GetComponent<RawImage>();
}

void Update()
{
  int index = (int)(Time.time * framesPerSecond) % frames.Length;
  image.texture = frames[index]; //Change The Image
}

I suggest you go with method 2 . This means that you have to delete the current Image in your scene. Then go to GameObject -> UI -> Raw Image and create a RawImage . Raw Image is efficient in this case because you are always changing the image. Using method 1 is slower and will unleash garbage collector in your game/app .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM