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?

2 Answers

2

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

–

Place awesome.png in Assets/Resources/ (you can have subfolders), and use:

GetComponent<SpriteRenderer>().sprite = 
    Resources.Load<Sprite>("awesome");  // No file extension.

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.

–