Casting Error C# between Object[] and Texture2D[]

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

public class BackChange : MonoBehaviour
{
	
	bool swap = true;
	public Texture2D[] files;

	void Start ()
	{
		//Line Below has ERROR
		files = (Texture2D[]) Resources.LoadAll("Frames");
		StartCoroutine ("textureSwap", 0.041);
	}
	
	IEnumerator textureSwap (float swapAfter)
	{
		int i;
		int num = 0;
	
		for (i = 1; i > 0; i++)
		{
			if (swap == true)
			{
				Texture2D file = files[num];
				GetComponent<RawImage>().texture = file;
				swap = false;
				Debug.Log (file);
				yield return new WaitForSeconds (swapAfter);
			}
			if (swap == false)
			{
				if (num < 168){
					num = num + 1;
				}else if (num >= 168){
					num = 0;
				}

				Debug.Log ("Ran!");

				swap = true;
			}
    		}
    	}
    }

Line 13 is where there is an error: files = (Texture2D[]) Resources.LoadAll(“Frames”);

My “Frames” folder is full of JPEG images which I have already used earlier as a Texture2D.

Here is the full error output: InvalidCastException: Cannot cast from source type to destination type.
BackChange.Start () (at Assets/Scripts/BackChange.cs:13)

This should be able to cast so I don’t know why I am getting this error.


Any help would be greatly appreciated!

Seems like it’s picking up more then Texture2D types. You can supply the type to the method to filter out anything undesired.

Change:

files = (Texture2D[]) Resources.LoadAll("Frames");

to

files = (Texture2D[]) Resources.LoadAll("Frames", typeof(Texture2D));

I changed my code to this:

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

public class Backtest : MonoBehaviour {

bool swap = true;
public Object[] frames;

void Start() {
	frames = Resources.LoadAll("Frames", typeof(Texture2D));
	StartCoroutine ("textureSwap", 0.041);
}

IEnumerator textureSwap (float swapAfter)
{
	int i;
	int num = 0;
	
	for (i = 1; i > 0; i++)
	{
		if (swap == true)
		{
			GetComponent<RawImage>().texture = (Texture) frames[num];
			swap = false;
			yield return new WaitForSeconds (swapAfter);
		}
		if (swap == false)
		{
			if (num < 168){
				num = num + 1;
			}else if (num >= 168){
				num = 0;
			}

			swap = true;
		}
	}
}

}

And now it works. I still don’t know why the previous cast I tried didn’t work but at-least now I have a solution. :smiley:

To anyone else with this problem I suggest you try to cast to “Texture” instead of “Texture2D” and see if that works.