1

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

Roaster84
  • 13
  • 3
  • I don't know Unity3D in details, but it looks to me `Text` is a UI element displaying text data. Therefore, a variable of type `Text` can only hold instances of type `Text`, not instances/values of type `string`. Visit the online Unity3D scripting/API documentation and try finding the respective API documentation for the `Text` type. Read what the purpose of this type is. And further peruse the documentation of the members (methods/properties) of the `Text` type to find which of its methods or properties will allow you assign a string value to a `Text` instance. –  Dec 15 '22 at 15:34

2 Answers2

4

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

Stephen Gilboy
  • 5,572
  • 2
  • 30
  • 36
KangarooRIOT
  • 691
  • 1
  • 7
  • 25
1

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 code ScoreText.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

thunderkill
  • 126
  • 5