- Home /
(C#) Help with Spriterenderer.sprite
I'm trying to figure out how to use this and I havent been able to search up too much information on it, the unity docs page is fairly useless.
What I want to do with it is have the spriterenderer load a various sprites when various variables are met, for example when my character jumps I want to change the idle sprite to a jump sprite. All my sprites are contained in a sprite sheet. Here is the script I've been working on for this, I pulled out empty methods and cleaned it up slightly.
using UnityEngine;
using System.Collections;
public class PlayerScript : MonoBehaviour {
public Sprite stickSprite;
GameObject pc;
bool wallContact = false;
bool facingRight = true;
SpriteRenderer pcSprite;
void Start (){
pc = GameObject.Find("Player");
pcSprite = pc.GetComponent<SpriteRenderer>();
stickSprite = Resources.LoadAll<Sprite>("Sprites/StickManSheet");
pcSprite.sprite = stickSprites["pcIdle"];
}
}
So please if someone would explain the SpriteRenderer.sprite workings to me I would be super appreciative.
Answer by Loius · Mar 04, 2014 at 07:41 AM
You can't (or couldn't when I tried) programmatically get complete listings of sprites outside of the Editor.
I have an Asset Store asset that creates SpriteSheets in the editor so you can do:
sprenderer.sprite = sheet.sprites[number]
As far as I know the only way to collect all sprites out of a "sprite" texture is this (you'll need "using System.Linq;"):
Object[] objects = AssetDatabase.LoadAllAssetRepresentationsAtPath(AssetDatabase.GetAssetPath(sourceTexture));
Sprite[] sprites = objects.Select(x=>(x as Sprite)).Where(x=>x.name.Contains(sourceTexture.name+"_")).ToArray();
What about just pulling a single sprite out of the sprite sheet. I've already cut it up, and if I manually assign the sprite to a sprite variable through the editor it works fine. Is there a way I can programmatically point towards the sprites in the sprite sheet?
Object[] objects = AssetDatabase.LoadAllAssetRepresentationsAtPath(AssetDatabase.GetAssetPath(sourceTexture));
Sprite[] sprites = objects.Select(x=>(x as Sprite)).Where(x=>x.name.Contains(sourceTexture.name+"_")).ToArray();
You just need to say
mySpriteRenderer.sprite = sprites[someIndex];
Answer by Dblfstr · Mar 04, 2014 at 07:09 PM
You should really use mecanim for sprite animations (that is what this is). You have an idle animation (can be just one sprite) and a jump animation (also does not have to be multiple sprites). You create a parameter in the animator (created when you make an animation for a sprite) call it hasJumped or isJumping (set to false by default), whatever, make it a trigger or a bool. In your script that controls the jump set the trigger to true to tell the animator to switch to that animation. animator.setTrigger(hasJumped, true) something like that.