26 de mai. de 2017

Changing the Sprites of a Character in Runtime

Do you have two or more characters in your game with the same structure, animation but you need to change its Sprites to make them look different?

Do you want to change the Sprite of a character in order to change its look, for example, just to change its clothes or objects that it's carrying?

Put this Component into your Character´s GameObject.
In the Inspector, change the spriteSheetName property to the name of your SpriteSheet Asset.
The Spritesheets must have the same "sliced" sprites name, for example: head, body, etc.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
using UnityEngine;
using System;

/*
 * This script changes the sprite of a gameobject in runtime
 * the sprites must be in the Resources folder
 * */
public class ChangeSprite : MonoBehaviour {

 public String spriteSheetName; // name of sprite to be loaded

 void LateUpdate () {
  var subSprites = Resources.LoadAll<Sprite>(spriteSheetName);
  
  foreach(var renderer in GetComponentsInChildren<SpriteRenderer>()) // get all SPriteRenderer from my GameObject
  {
   string spriteName = renderer.sprite.name;
   var newSprite = Array.Find(subSprites, item => item.name == spriteName);

   if (newSprite)
    renderer.sprite = newSprite;
  } 
 }

 
}

Nenhum comentário: