error CS0029: Cannot implicitly convert type `string' to `UnityEngine.UI.Text'

Hi, I’m following the Roll-a-ball tutorial and have hit a snag, despite following the instructions carefully. When attempting to edit my code to display “You Win!” text, I run into this error:

“Assets/scripts/playerController.cs(21,19): error CS0029: Cannot implicitly convert type string' to UnityEngine.UI.Text’”

I assume it has something to do with line 49:

countText.text = "Count: " + count.ToString ();

–but this line didn’t cause problems when I was creating the count–only now that I’m adding the “You Win!” text.
Also, as far as I can tell, I’ve followed the instructions.

Thanks for any help!

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

public class playerController : MonoBehaviour
{

    public float speed;
    public Text countText;
    public Text winText;

    private Rigidbody rb;
    private int count;

    void Start()
    {
        rb = GetComponent<Rigidbody>();
        count = 0;
        SetCountText();
        winText = "";
    }

    void FixedUpdate()
    {
        float movehorizontal = Input.GetAxis("Horizontal");
        float moveVertical = Input.GetAxis("Vertical");

        Vector3 movement = new Vector3(movehorizontal, 0.0f, moveVertical);

        rb.AddForce(movement * speed);
    }

    void OnTriggerEnter(Collider other)
    {

        if (other.gameObject.CompareTag("Pick Up"))
        {
            other.gameObject.SetActive(false);
            count = count + 1;
            SetCountText();
        }

    }

    void SetCountText ()
    {

        countText.text = "Count: " + count.ToString ();
        if (count >= 12)
        {
            winText.text = "You Win";
        }

    }

}

The error comes from line 21. You need to include the “text” variable of the Text component.

winText.text = "";
1 Like

As the error indicates, you are attempting to convert a string into a Text object, on line 21.
You want to assign the string to the .text attribute of the Text object, as Intense_Gamer94 indicates.

1 Like

I see, thanks a lot!

While I’m here, is anyone up for explaining this line (49) to me?

"countText.text = “Count: " + count.ToString ()”

It’s the only line I couldn’t really understand why I wrote it–particularly “count.ToString ()”.

I see maybe–“count.ToString ()” is telling it to convert the count variable integer into a text string in order to display it?

Yep, ToString() converts to a string.

This isn’t necessary in your case because you have the “Count:” string before so it converts automatically. Something like this would work the same:

countText.text = "Count:" + count;
1 Like

Great, thanks for help!