Reputation: 11
I want to change the image that clicked image button. so, I set a button and try to load a PNG file at assets/Resources/ PATH. But it always return and it makes me massed up -_-. Some of questions likes my situation, everybody answers 'try to move file to load assets/Resoucres PATH and my situation couldn't be fixed that way.
Here is my code. This function is load a NumCard_1.png file when clicked a image button. NumCard_1.png exists at assets/Resources folder.
void OnclkMe()
{
Sprite newSprite = Resources.Load<Sprite>("/NumCard_1") as Sprite;
// I already try ("NumCard_1") instead above.
if(newSprite==null)
{
Debug.Log("NULL"); // Always prints "NULL" -_-.
}
else
{
Debug.Log(newSprite.name);
}
}
Upvotes: 1
Views: 3574
Reputation: 1512
Maybe you don't set import config of that file into sprite? Normally png would be imported as texture, not sprite
First you should try to check it like this
var obj = Resources.Load("NumCard_1");
Debug.Log(typeof(obj));
If obj is not null, it would tell you what type it is. If it not sprite you would need to go to unity editor, select file, and change import type that png into sprite
ps Using generic mean you can just write is like this
var obj = Resources.Load<Sprite>("NumCard_1");
And obj will be sprite. If it not a sprite it would be null
Upvotes: 0
Reputation: 356
When using Resources.Load in Unity, it uses a relative folder to "Resources" every resource you intend to use at runtime must be located under /Resources, if it ain't there - create it. after you create this base folder (under Assets) you can create subfolders by your own preference.
secondly, Resources.Load("/NumCard_1") as Sprite is kind of misused. the generic method Resources.Load returns T so you can drop the "as Sprite" (it will act the same).
as Unity uses "Resources" as base folder you should remove the "/" before "NumCard". if you use subfolder you might want to specify the path as "Cards/NumCard_1".
as per your code, after creating the folder Assets/Resources and placing the img in it, try the following:
Sprite newSprite = Resources.Load<Sprite>("NumCard_1")
Upvotes: 3
Reputation: 31
Add your sprite in resources folder. Change texture type to Sprite, and apply.
Sprite newSprite = Resources.Load("NumCard_1",typeof(Sprite)) as Sprite;
Upvotes: 0