- Home /
Struggling to change the sprite on the SpriteRenderer through code?
Hey guys,
Trying to get used to the new Unity 2D stuff and I'm struggling with changing the sprites in the SpriteRenderer dynamically. Here's the code I'm using:
Object loadedObject = Resources.Load(filePath);
Sprite spriteObject = (Sprite)loadedObject;
SpriteRenderer spriteRenderer = GetComponent<SpriteRenderer>();
spriteRenderer.sprite = spriteObject;
So the loadedObject isn't null so it's definitely loading something but it's just loading the Texture2D (which is logical since the filePath is pointing at a .png). When I try to cast it as a sprite it fails and spriteObject is null. My question is how do I get a sprite out of this that I can set on a SpriteRenderer? Is it possible?
Some more info: The import settings on the png are set to importing as a sprite, if i drag and drop the .png in the scene it appears as a sprite. I can see the sprite in the Project view as an object under the .png, is it this I should be accessing? How do I load that?
Thanks in advance for any help!
Answer by _Geo_ · Nov 14, 2013 at 03:21 PM
Think I was being an idiot, just needed to use:
Resources.Load<Sprite>(filePath);
and it loaded the sprite fine!
Answer by infinitypbr · Jan 06, 2014 at 09:17 PM
http://forum.unity3d.com/threads/211817-Changing-sprite-during-run-time
Eric5h5's answer, which is what I think you're actually looking for?
var newSprite : Sprite;
function Start () {
GetComponent(SpriteRenderer).sprite = newSprite;
}
@Geo :How it possible on mouse over the image.
function On$$anonymous$$ouseEnter() { GetComponent(SpriteRenderer).sprite = newSprite; }
is this possible?