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?
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.
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.”