- Home /
Unityscript Textfield Error
Hey guys, I'm pretty new to Unity, but I've been learning pretty quick. I'm having trouble making some text appear properly,
var ammo;
var remainingammo;
var remainingfont : GUIStyle; // This font is 20px
ammo = 100;
remainingammo = ammo*1.8;
GUI.TextField(Rect(645,Screen.height-38,80,30),remainingammo,remainingfont);
The problem I'm getting is "InvalidCastException: Cannot cast from source type to destination type." What I'm trying to have it do is to print the number over an ammo bar, and as the ammo is used, the number goes down. What I have provided is only a fraction of the whole code, but if it's necessary to help you solve this, I can post the whole code. Does anyone have any insight on my problem?
Thanks in advance.
Try statically typing everything, and then use
remainingammo.ToString()
ins$$anonymous$$d of just 'remainingammo' in your GUI call. The problem is that the GUI call needs a string, and 'remainingammo' might not actually be one.
Thanks for the comment syclamoth, I tried your idea and unfortunately it didn't work, but thanks for giving an idea!
Answer by kolban · May 11, 2012 at 01:26 AM
If we look at the documentation for the method GUI.TextField() we see that the format you are using wants:
Rect, String, GUIStyle
as the three parameters.
However, your variable, remainingammo is of data type "float" and that is probably what is causing the type error. Try the following as your code:
GUI.TextField(Rect(645,Screen.height-38,80,30),"" + remainingammo,remainingfont);
Note the usage of the String append as a converter.
Your answer
![](https://koobas.hobune.stream/wayback/20220613071341im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
A node in a childnode? 1 Answer
Need help with screen resolution and character size 1 Answer
FBX file animation problem 0 Answers
Rotation problem 1 Answer
Building Game w/ Scriptable Objects 1 Answer