I optimized some of your code and debugged the Guessed() function, and it worked. Sure that no other component is changing the sprite?
Here’s the code:
public class ShowColor : MonoBehaviour
{
#region Variables
public GameObject colorMeaningTextObject;
public GameObject textColorTextObject;
public GameObject textColorBox;
public Sprite rightAnswerSprite;
public Sprite wrongAnswerSprite;
public Sprite defaultSprite;
readonly List<KeyValuePair<int, string>> colors = new List<KeyValuePair<int, string>>()
{
new KeyValuePair<int, string>(1, "amarelo"),
new KeyValuePair<int, string>(2, "azul"),
new KeyValuePair<int, string>(3, "vermelho"),
new KeyValuePair<int, string>(4, "verde"),
new KeyValuePair<int, string>(5, "cinza"),
new KeyValuePair<int, string>(6, "branco"),
new KeyValuePair<int, string>(7, "rosa"),
};
readonly List<Color> textColors = new List<Color>()
{
new Color(1, 0.9f, 0, 1),
new Color(0.14f, 0.14f, 1, 1),
new Color(1, 0.1f, 0.1f, 1),
new Color(0, 0.8f, 0, 1),
new Color(0.5f, 0.5f, 0.5f, 1),
new Color(1, 1, 1, 1),
new Color(1, 0, 0.5f, 1)
};
int colorMeaningCode;
int textColorMeaningCode;
int textColorColorCode;
bool isAnswered = false;
Image clrBoxImg = null;
#endregion
void Awake() => clrBoxImg = textColorBox.gameObject.GetComponent<Image>();
void Start()
{
clrBoxImg.sprite = defaultSprite;
NewTextColors();
}
void NewTextColors()
{
isAnswered = false;
Text colorMeaning = GameObject.Find("colorMeaningText").GetComponent<Text>();
Text textColor = GameObject.Find("textColorText").GetComponent<Text>();
colorMeaningCode = Random.Range(1, 8);
textColorColorCode = Random.Range(1, 8);
textColorMeaningCode = Random.Range(1, 8);
foreach (var item in colors)
{
if (item.Key == colorMeaningCode) colorMeaning.text = item.Value;
if (item.Key == textColorMeaningCode) textColor.text = item.Value;
if (item.Key == textColorColorCode) textColor.color = textColors[item.Key];
}
}
public void Guessed(bool guessed)
{
bool isColorSame = colorMeaningCode == textColorColorCode;
clrBoxImg.sprite = (guessed == isColorSame) ? rightAnswerSprite : wrongAnswerSprite;
isAnswered = true;
}
void Update()
{
if (isAnswered)
{
NewTextColors();
isAnswered = false;
}
}
}