- Home /
noob coding mistake, please help
Hey, so i want to have a score system in my game, and the score goes down as you play so the faster you finish the higher your score will be. i have got the following code which i applied to a Guitext. the code starts off at 5000 and counts down in 1's every tick but i cant find a way of having the GUI text show the number. here are the relevant images and the error i get.
the empty i made GUI Text on (http://i.imgur.com/yvCc3pi.png)
The Code (i'm using C#) using UnityEngine; using System.Collections;
public class Score : MonoBehaviour {
public float score;
public GUIText yourText;
// Use this for initialization
void Start () {
score = 5000;
}
// Update is called once per frame
void Update () {
score = score - 1;
yourText.text = score;
}
}
and i get this error when trying to build it, "cannot implicitly convert type float
to string
" and this is on the line "yourText.text = score;" thank you for your help.
Answer by tanoshimi · Mar 17, 2015 at 09:47 PM
You can't implicitly convert a float to a string. So do it explicitly:
yourText.text = score.ToString();
Thank you so much, as title stated it was a noob mistake :) i was trying things like .string thank you so much for your help works as intended now :)
Answer by mpennin3 · Mar 17, 2015 at 10:07 PM
Why dont you just look at Beginner Roll-a-Ball at http://unity3d.com/learn/tutorials/projects/roll-a-ball/Displaying-text and fast forward to where he shows the code for it because the problem is the text.
Answer by dr3th · Mar 17, 2015 at 09:48 PM
Hi TurbidWarrior,
Lets break this down.
1 "cannot implicitly convert type float to string" Score is of type float. youText.Text property is of Type string.
To fix this first error:
void Update () {
score = score - 1;
yourText.text = score.ToString();
}
2 Do not use GUIText(It's no longer supported) but instead use UnityEngine.UI.Text. Please add a Text Component to your game.
void Update()
{
score--;
GameObject DrethScoreGameObject = GameObject.Find("yourText");
Text yourText= DrethScoreGameObject.GetComponent<Text>();
yourText.Text = score.ToString();
}
Your answer
