- Home /
'Cannot convert int to String'
Odd problem here.
Whenever the player kills an enemy, the player gets gold. I wanted to have the gold popup by the enemies death "+[gold]", which I've sort of done so far. I'm using a 3D text object for that, and now I'm trying to set the gold earned to the 3d text, but it's telling me I cant convert it to a string. Maybe I'm doing something wrong as I'm only just a beginner.
function addGold(){
plusPlayerGold = Random.Range(190, 300) * difficultyGoldMultiplier;
playerScript.playerGold += plusPlayerGold;
plusPlayerGold.ToString();
goldText.guiText.text = plusPlayerGold;
Instantiate(goldText, transform.position, transform.rotation);
}
Also I'm not fully sure if goldText.guiText.text = plusPlayerGold; is the correct code, it was a half guess to be honest. That is the line that's giving me the error, too.
Answer by Landern · Nov 29, 2012 at 01:33 PM
When you did ToString() on the int, you didn't assign it to anything, you performed the extension method, but ToString() returns a type of string, if you are not assigning it to anything, it ends up wasted work. I mean after all, with how it was programmed, you would expect that the plusPlayerGold type after using ToString suddenly changes times from an int to a string... wait actually that makes sense, but isn't how it works.
function addGold(){
plusPlayerGold = Random.Range(190, 300) * difficultyGoldMultiplier;
playerScript.playerGold += plusPlayerGold;
// plusPlayerGold.ToString(); // bad, not assigned
goldText.guiText.text = plusPlayerGold.ToString();
Instantiate(goldText, transform.position, transform.rotation);
}
Oh wow okay, thankyou. That's fixed now, but I just realized, I was trying to access my 3D text through guiText. I don't know how to access the 3D text, is there a way to do that?
Answer by Dave-Carlile · Nov 29, 2012 at 01:34 PM
ToString() is a function that returns the value as a string. Calling it like you do - plusPlayerGold.ToString() - without assigning the result to something doesn't accomplish anything. You want this:
goldText.guiText.text = plusPlayerGold.ToString();
And remove the previous line where you call ToString().