- Home /
How do I replace a sprite in script?
I'm trying to replace a gameobject's sprite via script. I can't seem to find a way to do it. I've attempted replacing the texture after loading it via resources, but it doesn't help.
This is what I'm trying to do:
Texture2D texture = Resources.Load<Texture2D>("Wall_Vertical");
wall.renderer.material.SetTexture("Wall_Vertical", texture);
Since 4.3 released very recently there isn't much info out there. Anyone got an idea?
Answer by Skitzomaniak · Dec 11, 2013 at 06:45 PM
The easiest way I've found so far:
Sprite spr = Resources.Load<Sprite>("SpriteName");
SpriteRenderer sprRenderer= (SpriteRenderer)renderer;
sprRenderer.sprite = spr;
No amount of fiddling around with the renderer's material got me anywhere, but getting the GameComponent's SpriteRenderer and just applying the sprite directly to it seems to work. I have no idea how this method is for performance, but it works.
Thank you this worked for me
I am trying to make a card game with playing cards and did not wnat 52 textures, this seems like i can mix numbers and a picture to represent suit.
And after a qick look i also found the next pice i wanted to be able to make the numbers red or black to make it easier to tell suit i used this pice of code
sprRenderer.color = new Color (1, 0, 0, 1);
at the end of Skitzomaniak's code to make it red
i found the info here
http://answers.unity3d.com/questions/56924/changing-a-materials-color-in-c.html
Answer by anisabboud · Mar 27, 2015 at 10:10 PM
Place awesome.png
in Assets/Resources/
(you can have subfolders), and use:
GetComponent<SpriteRenderer>().sprite =
Resources.Load<Sprite>("awesome"); // No file extension.
http://docs.unity3d.com/ScriptReference/Resources.html
There's also LoadAll that "Loads all assets in a folder or file at path in a Resources folder."
Sorry for reviving this, but you cannot have sub folders inside the resources folder. You can however put the resources folder inside a sub folder inside the assets folder.
Well, you should be sorry, because you're wrong. You CAN have subfolders in Resources.
It has been a feature since 7+ years ago.
http://answers.unity3d.com/questions/22180/loading-resources-from-folder-in-project-to-hierar.html
Your answer
![](https://koobas.hobune.stream/wayback/20220613122032im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
A node in a childnode? 1 Answer
itween move to do not end(even it is) 0 Answers
checking two seperate objects collision 0 Answers
Fps Aiming Script help 2 Answers