I am new to Unity so Im making a flappy bird game to learn the basics. When creating the score, I had to tranform an int variable int oa string variable, but it doesnt work. Here is the code (Written in Visual Studio):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class LogicScript : MonoBehaviour
{
public int PlayerScore;
public Text ScoreText;
public void addScore()
{
PlayerScore = PlayerScore + 1;
ScoreText = PlayerScore.ToString();
}
}
The ToString method at the end doesnt work. It gives me the following error: You cannot transform type string in UnityEngine.UI.Text. I dont understand it. I dont know a lot of Unity so some help would be apreciated. Thanks!
I was trying to make a flappy bird score. I tryed making a variable with that information (string PlayerScoreText = PlayerScore.ToString();), finding other methods that could help, closing and reopening the game and trying to understand what the error means but I dont know whats wrong
2
Answers
It looks like what you’re doing is 90% correct but you are missing your ScoreText is needing the .text after it.
Try:
ScoreText.text = PlayerScore.ToString();
The Unity documentation shows it also like this. https://www.tutorialspoint.com/unity/unity_text_element.htm
the fix is easy my friend
Text ScoreText
refers to the Text component but you need to access the text area attribute in the Text Component ScoreText so to do so you need to put this codeScoreText.text = PlayerScore.ToString();
the part where you where wrong isn’t the parsing of the int but tryin to affect a string to a UI component