- Home /
Multiple If Statements causing problems with changing sprites
Hey so I'm having problems getting different sprites to show up depending on a gameobjects tag. The problem seems to come from having multiple if statements checking the objects tag for all the different sprites, here's an excerpt from the script that worked fine:
public GameObject Canada;
public Sprite CanadaUN;
void Start()
{
Canada.tag = "UNZone";
}
void Update()
{
if (Canada.tag == "UNZone")
{
Canada.GetComponent<SpriteRenderer>().sprite = CanadaUN;
}
}
But it seems when I add more sprites and make more if statements like above to have them show up if the tag changes it stops working. Any ideas?
First, don't compare string in Update() like that, it's expensive. Do the tag change mid-play in-game and you need to check its tag every Update() like that?
Secondly, post the code that you added more if statements, I don't see anything wrong here yet
I'm not sure what you mean in the first part, I'm still pretty new to all this. Here's the rest:
public GameObject Canada;
public Sprite CanadaUN;
public Sprite CanadaAL;
public Sprite CanadaDO;
public Sprite CanadaGI;
public Sprite CanadaVA;
void Start()
{
Canada.tag = "UNZone";
}
void Update()
{
if (Canada.tag == "UNZone")
{
Canada.GetComponent<SpriteRenderer>().sprite = CanadaUN;
}
if (Canada.tag == "ALZone")
{
Canada.GetComponent<SpriteRenderer>().sprite = CanadaAL;
}
if (Canada.tag == "DOZone")
{
Canada.GetComponent<SpriteRenderer>().sprite = CanadaDO;
}
if (Canada.tag == "GIZone")
{
Canada.GetComponent<SpriteRenderer>().sprite = CanadaGI;
}
if (Canada.tag == "VAZone")
{
Canada.GetComponent<SpriteRenderer>().sprite = CanadaVA;
}
}
If you mean doing the tag checks like that is expensive that is probably the problem because I have a bunch more for all the different gameobjects that I need to change sprites for in the same way, never seen it done any other way though.
how did you set its tag? Do you set it in the editor's inspector?
Answer by revolute · Oct 30, 2019 at 10:57 AM
[System.Serializable]
public class Tag{
public string tag;
public Sprite sprite;
}
public List<Tag> tagList = new List<Tag>();
will let you work with the tags and sprite matching in the inspector.
Then, loop through the list to check if any matches.
foreach(var i in tagList){
if(Canada.tag == i.tag)
Canada.GetComponent<SpriteRenderer>().sprite = i.sprite;
}
Thanks for the reply, hope it can help someone in the future. Turns out my problem was that I hadnt assigned all the gameobjects in the inspector, I have quite a few on that script so I didn't want to assign all of them if it wouldn't work, turned out that was the issue