- Home /
Change Sprite within an image component with a script
I am using javascript to create a script to change a sprite in a UI image box for a tic tac toe game. My current code is just to change back and forth between two sprites both located in Assets/pictures/sprites folder. Here is my code:
#pragma strict
var Image : UnityEngine.UI.Image;
var flip = true;
function Start () {
}
function Update () {
if(flip){
flip = false;
Image.sprite = Resources.Load ("o_green") as Sprite;
//Debug.LogWarning(flip);
}
else {
flip = true;
Image.sprite = Resources.Load ("o_red") as Sprite;
//Debug.LogWarning(flip);
}
}
Here is my setup in the Unity editor:
I have tried changing the path to "pictures/sprites/o_red" but still it does not change the sprite when running the game. Am I getting the path wrong? Or am I approaching this the wrong way?
Answer by KickBack · Mar 05, 2015 at 11:19 AM
Resources.Load can only load assets that are placed inside a folder named Resources. (Or from subfolders inside this one) Move your sprites inside this folder then you can load them from there. for example if the image is at "Resources/pictures/sprites/o_red.png" the argument should be "pictures\sprites\o_red"
This worked! thank you! note: i changed my code to be like this "Image.sprite = Resources.Load ("o_red", typeof(Sprite));" and created a 'Resources' folder and put the 'o_red' sprite in the 'Resources' folder.
Your answer
Follow this Question
Related Questions
Loading Built-in resources 0 Answers
Can someone help me fix my Javascript for Flickering Light? 6 Answers
Strange smearing on texture with unity 4.3.4 1 Answer
Resources.Load(filename) as Sprite is returning null 2 Answers
Resources not loading in APK 0 Answers