- Home /
Easy sprite finding script
I'm making a 2D game and have this script attached to my slime:
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class slimehealthbar : MonoBehaviour {
public int slimehealth;
public Sprite shp99;
public Sprite shp98;
public Sprite shp97;
public Sprite shp96;
public Sprite shp95;
public Sprite shp94;
public Sprite shp93;
(ect.)
// Use this for initialization void Start () {
slimehealth = 99;
}
// Update is called once per frame
void Update () {
if (slimehealth == 99) {
this.gameObject.GetComponent<SpriteRenderer>().sprite = shp99;
}
if (slimehealth == 98) {
this.gameObject.GetComponent<SpriteRenderer>().sprite = shp98;
}
if (slimehealth == 97) {
this.gameObject.GetComponent<SpriteRenderer>().sprite = shp97;
}
if (slimehealth == 96) {
this.gameObject.GetComponent<SpriteRenderer>().sprite = shp96;
}
if (slimehealth == 95) {
this.gameObject.GetComponent<SpriteRenderer>().sprite = shp95;
}
if (slimehealth == 94) {
this.gameObject.GetComponent<SpriteRenderer>().sprite = shp94;
}
if (slimehealth == 93) {
this.gameObject.GetComponent<SpriteRenderer>().sprite = shp93;
}
(ect.)
I was wondering if there was an easier way of assigning sprites to variables and then applying that to a health script... Any help will be much appreciated! Thanks...
P.S. Shp = slime hp
Answer by goutham12 · Oct 09, 2017 at 06:59 AM
public list SPlist; void Start(){ this.gameObject.GetComponent().sprite = SPlist[slimehealth - 99];
}
Note: your order shoudbe 99,98,...
public List<Sprite> Splist;
public int slimehealth;
SpriteRenderer spRender;
void Start () {
spRender=this.gameObject.GetComponent<SpriteRenderer> ();
spRender.sprite = Splist [99 - slimehealth];
}
i tested it is working.
Your answer
Follow this Question
Related Questions
How can I change this script to use GUITexture instead of GUI number, for health display? 1 Answer
health script do not work when collision detected 1 Answer
Instantiate health bar with networking 2 Answers
Health bar 1 Answer
Health Points 1 Answer