Search code examples
arraysunity-game-enginetexture2d

Load PNG images to array and use as textures


I've been attempting to use PNG images as textures in Unity, when I use only one or two its easy to drag and drop them in the inspector. In my current project I have over 300 images which I am trying to load into an array, I then want to change the texture each time round the update so it appears like a video.

Here is what I have so far:

using UnityEngine;
using System.Collections;

public class ChangeImage : MonoBehaviour {

public Texture[] frames;
public int CurrentFrame;
public object[] images;

    void OnMouseDown() {
        if (GlobalVar.PlayClip == false){
            GlobalVar.PlayClip = true;          
        } else {
            GlobalVar.PlayClip = false;         
        }
    }   

    public void Start() {

        images = Resources.LoadAll("Frames");

        for (int i = 0; i < images.Length; i++){
            Texture2D texImage = (Texture2D) images[i];
            frames[i] = texImage;
        }
    }

    // Update is called once per frame
    void Update () {
        if(GlobalVar.PlayClip == true){
            CurrentFrame++;
            CurrentFrame %= frames.Length;
            GetComponent<Renderer>().material.mainTexture = frames[CurrentFrame];
        }
    }   


}

I have been attempting to load the images into an object array convert them to textures then output to a texture array. Does anyone know where I am going wrong with this it does not seem to give any errors but the texture is not changing?

Any advice is much appreciated

Thanks


Solution

  • I managed to fix the problem eventually, the problem seemed to be the loading of assets was not working correctly and this was why the frame was not changing. I also changed the name of the folder containing the images from "Frames" to "Resources". Here is the completed code for anyone else who needs it:

    using UnityEngine;
    using System.Collections;
    
    public class ChangeImage : MonoBehaviour {
    
    public Texture[] frames;
    public int CurrentFrame;
    
        void OnMouseDown() {
            if (GlobalVar.PlayClip == false){
                GlobalVar.PlayClip = true;          
            } else {
                GlobalVar.PlayClip = false;         
            }
        }   
    
        public void Start() {
            frames = Resources.LoadAll<Texture>("");
        }
    
        // Update is called once per frame
        void Update () {
            if(GlobalVar.PlayClip == true){
                    CurrentFrame %= frames.Length;
                    CurrentFrame++;
                    Debug.Log ("Current Frame is " + CurrentFrame);
                    GetComponent<Renderer>().material.mainTexture = frames[CurrentFrame];               
                }
    
            }
    
    }
    

    Thanks for the advice on animations I will still look into it as the performance of the images is not great.