Here is my code. I have looked at other post, but I can't find anything.
GetComponent(inGameText).text = money.ToString();
I also have a text variable:
public Text inGameText;
And I don't know if I have to have it as a GameObject Or not.
I also don't know if the TextMesh part is a placeholder or not because I got it off another post.
CodePudding user response:
There are different overloads of GetComponent
You either pass in a type but then you need to cast
inGameText = ((Text)GetComponent(typeof (Text)));
or you use the generic
inGameText = GetComponent<Text>();
However, in your case you seem to already have the reference and simply want to use
inGameText.text = money.ToString();
and eventually use one of before methods to assign the value to inGameText if not done via the Inspector
CodePudding user response:
The GetComponent function does the following: given the type of UnityEngine.Component it returns the first instance of that type or derivate -if any- on the GameObject you're calling that function from. For instance, if you have added in the inspector a Text component on a certain GameObject it can be returned by a call of gameObject.GetComponent.
The version of the function you're trying to use is defined like this: Component GetComponent(Type type). It means it needs a parameter representing the type of the component you're interested in and returns a generic Component reference, that you then need to explicitly cast to the actual type. To get a Type value you can either call GetType() on any non-null variable or use typeof(<name_of_the_type).
In order to do what you're trying to do, this is the syntax to use:
((Text)GetComponent(typeof(Text))).text = money.ToString()
Although, since you already have a public Text variable I'm assuming you also assigned it a value from the Inspector, meaning you don't need to actually call GetComponent to give it a text value, but it would suffice to write
inGameText.text = money.ToString();
A thing I'd like to point out is that you also have an alternative to Component GetComponent(Type type), which is the much more readable T GetComponent<T>(). If you're not very familiar with generics, I'd suggest to look into them because they're foundamental for good programming in C#. But in this case you basically have to read this as: this is a function which returns something of type T, where T is something I decide by specifying it between the <>. In short, your code would become
GetComponent<Text>().text = money.toString();
Notice that with this version of the function you don't need to extrapolate the type of Text using typeof and you don't need to explicitly cast the result to Text, because using generics you already told the function precisely what you want.
