- Home /
Help With Hats?
I can't seem to find the problem of why it wont work, I can't see problems in my code but all it does is change to "Ilan" and i can't change it with HatNO Here's my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Hats : MonoBehaviour
{
public int HatNO;
public Sprite None;
public Sprite Kid;
public Sprite Becc;
public Sprite Lucy;
public Sprite Lucas;
public Sprite Jameson;
public Sprite Ilan;
void Update()
{
if(HatNO == 0);
{
this.gameObject.GetComponent<SpriteRenderer>().sprite = None;
Debug.Log("0");
}
if(HatNO == 1);
{
this.gameObject.GetComponent<SpriteRenderer>().sprite = Kid;
Debug.Log("1");
}
if(HatNO == 2);
{
this.gameObject.GetComponent<SpriteRenderer>().sprite = Becc;
Debug.Log("2");
}
if(HatNO == 3);
{
this.gameObject.GetComponent<SpriteRenderer>().sprite = Lucy;
Debug.Log("3");
}
if(HatNO == 4);
{
this.gameObject.GetComponent<SpriteRenderer>().sprite = Lucas;
Debug.Log("4");
}
if(HatNO == 5);
{
this.gameObject.GetComponent<SpriteRenderer>().sprite = Jameson;
Debug.Log("5");
}
if(HatNO == 6);
{
this.gameObject.GetComponent<SpriteRenderer>().sprite = Ilan;
Debug.Log("6");
}
}
}
Answer by UnityM0nk3y · Apr 05, 2021 at 10:21 AM
Firstly, you made this error:
if(HatNO == 0);
{
}
//Change that to this:
if(HatNO == 0)
{
}
Now I would suggest you use a "Public Event" to change your hats, instead of doing it on Update.
If you don't know how, just ask. =)
Thank you! I got it to work, asked this elsewhere and they couldn't see the problem so I'm glad you pointed it out to me.
Awesome man, glad to hear!!
Just to explain a bit more: Running this code in "Update". Means that Unity will Change your hat to "HatNO", EVERY FRAME for the entire game. (You will receive "Infinite" Logs).
To prevent that, rather call "Change Hat" as a "Event".
Something like this:
public SpriteRenderer hatRenderer; //Assign this in Unity Engine, to your "HatRenderer"... (The "SpriteRenderer" that you use for the hats)
public Sprite[] hatSprites = new Sprite[6]; // we only need 6 hat sprites, as we can call "No Hat" as "NULL", and it needs no "Empty Sprite".
public void changeHat(int HatNO)
{
if (HatNO== 0) // no hat
{
hatRenderer.sprite = null;
}
else // use input directly to change hat with array indext
{
hatRenderer.sprite = hatSprites[HatNO -1];
}
}
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Input.mousePoition for controllers 0 Answers
Brackeys EnemyAi Script 0 Answers