- Home /
how to change texture for animation?
Hello, i'm making a game about slimes and there is a lot of types of them. i have single prefab for all the types and my plan is to have the same animation for all of them, but just change the texture depending on the type. So i have several identical sprite sheets, but in different colors for the different slime types. I hope you know what i mean.
So please, does anybody know how to change the texture for an animation using code, or if it is even possible?
Thanks, Villfuk
Answer by $$anonymous$$ · Aug 15, 2017 at 10:45 PM
If you name all of your sliced sprite variations the same thing you can iterate through and replace them an a late update, just put your sprite sheets in your Assets/Resources folder and you can load them at runtime:
using UnityEngine;
public class ReskinAnimator : MonoBehaviour
{
[SerializeField]
private string spriteSheetName; //this will be the name of your spritesheet, no file extension
void LateUpdate()
{
foreach (var renderer in GetComponents<SpriteRenderer>())
{
string spriteName = renderer.sprite.name; //finds the name of the sprite to be rendered
var subSprites = Resources.LoadAll<Sprite>(spriteSheetName); //loads all the sprites in your new sprite sheet
foreach (var sprite in subSprites)
{
if (sprite.name == spriteName) //if the sprite has the same name as one you're trying to replace than replace it
{
renderer.sprite = sprite;
}
}
}
}
}
So if i had the characters sprite sheet with idle, run etc as a PNG online and i downloaded it at runtime could i swap the skin of the character using your method this way?
Answer by Villfuk02 · Jul 12, 2017 at 12:03 PM
somebody please help, i really don't want to make the same animation fifty times.
There must be a more efficient way.
Your answer
Follow this Question
Related Questions
2D cube material pattern not repeating 1 Answer
Sprite.Create is not working 1 Answer
2D tiled background and scrolling (is this bad?) 1 Answer
Eliminate GUITexture Excess? 1 Answer
Accessing a Variable From Another Script 2 Answers