- Home /
The question is answered, right answer was accepted
Initialize a field with a value from a component?
Hi there!
I have a GameObject which is an InputField. It has a Text component which has a "text" value.
Right now I am initializing a GameObject field:
public GameObject message;
And drag&drop the InputField into that field in the Inspector. In order to read and write that text value I need to write
message.GetComponent<Text>().text = "something";
every time.
Is there any way to maybe initialize something like that?
public GameObject.GetComponent<Text>().text message;
So that I could address the text simply by
message = "something";
Thank You.
Answer by Hellium · Apr 23, 2018 at 03:57 PM
Simply declare your message
variable as follow:
public Text message;
Drag & drop the GameObject holding the Text
component in the inspector, and you will be able to edit the value like this:
message.text = "something";
It worked! Thanks a lot!
But - just in case - is it possible to shorten it even more so that I could use just "message" ins$$anonymous$$d of "message.text"?
Components can be variables, properties not.
".text" is a property of the component Text.
So.. nope :D
Unfortunately, you can't just declare a string
and make the content of your Text
change when you modify the string. It's because string
is a value type, not a reference type.
You can create a C# property (getter / setter) if you don't want to bother with typing message.text
each time:
public Text message;
public string $$anonymous$$essageContent
{
get { return message.text ; }
set { message.text = value ; }
}
// Elsewhere in your code:
$$anonymous$$essageContent = "hello world"; // the setter will be called and the `Text` component will be modified
Your answer
![](https://koobas.hobune.stream/wayback/20220612161346im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Initialising List array for use in a custom Editor 1 Answer
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Inspector vs Script: Component best practice? 1 Answer
Development of the shop? 1 Answer