Search code examples
stringunity-game-enginetexttype-conversioninteger

Why can't I set a Unity.UI.Text object to a string?


So I am trying to create a score counter for my game, and i want it to increment every time and enemy is killed. However when I try and set the score to its previous value + 1 I get an error stating:
error CS1503: Argument 1: cannot convert from 'UnityEngine.UI.Text' to 'string'

Here is my code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;


public class ShieldController : MonoBehaviour
{
    Text score;

    bool shot = false;

    public void LaunchForward(float speed)
    {
        shot = true;
        this.GetComponent<Rigidbody2D>().velocity = transform.up * speed;
    }

    void Start() {
        score = GameObject.Find("Canvas/Text").GetComponent<Text>();
    }

    void OnCollisionEnter2D(Collision2D other) {
        if (shot) {
            Destroy(gameObject);
            Destroy(other.gameObject);
            score.text = (int.Parse(score) + 1).ToString();
        }
    }
}

The text is set to "0" at the start. Why am I getting this error?


Solution

  • The problem is that you are parsing the score object which is the UnityEngine UI Text component, instead change it to :

    score.text = (int.Parse(score.text) + 1).ToString();
    

    I would also recommend having a separate score integer variable to store the score. So you would have scoreText as UnityEngine UI Text & score as Integer then you could do something like:

    score++;
    
    scoreText.text = $"{score}";
    

    Side Note:

    Please do not use these kind of assignments :

    score = GameObject.Find("Canvas/Text").GetComponent<Text>();
    

    For this specific case, you could assign the text component from UnityEditor by adding this:

    [SerializeField] private Text score;
    

    And get rid of what you're doing in the Start function.