Search code examples
c#unity-game-engineflappy-bird-clone

When making a score for a flappy bird clone, it gives an error when tranforming an int variable to a string one to display it in a text


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


Solution

  • 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