- Home /
C# Error when trying to load Texture at runtime
I am trying to load a random texture when an event is triggered in my game. In the Resources folder I have a sub folder with three textures: Card1.png Card2.png Card3.png
I have the following script:
int cardId = Random.Range(1, 3);
string assetPath = string.Format("Card{0}.png", cardId);
textureHolder.renderer.material.mainTexture = Resources.Load(assetPath, typeof(Texture));
But this throws the following error:
Cannot implicitly convert type `UnityEngine.Object' to `UnityEngine.Texture'. An explicit conversion exists (are you missing a cast?)
I have looked at the documentation for Resources.Load (http://docs.unity3d.com/ScriptReference/Resources.Load.html) but cannot figure out what I am doing wrong??
Any suggestions would be greatly appreciated! TIA!
Comment
Best Answer
Answer by Landern · Jul 08, 2014 at 03:26 PM
Resources.Load returns type of object, you need to type cast what that object is if you are going to use it in such a way that the type matters.
int cardId = Random.Range(1, 3);
string assetPath = string.Format("Card{0}.png", cardId);
textureHolder.renderer.material.mainTexture = (Texture)Resources.Load(assetPath, typeof(Texture));