How to set a variable to an item in the Hierarchy with a c# Script

Updated on May 1, 2017 in  [R] Scripts
Share on Facebook0Tweet about this on TwitterShare on Google+0Share on Reddit0
2 on May 1, 2017

Hey guys.
Like the heading says – How do I set a variable to an item in the Hierarchy? For Example:
I have an text item named “FunnyBunny”, and i want to use this in:


public Text funnyBunny;

How would i set it? Something like this?


public Text funnyBunny = ??????

What would I type at the ‘?’.
Thanks For all the replies!

  • Liked by
Reply
0 on May 1, 2017

Nothing you can’t initialize Unity only datatypes from outside of a method

  • Liked by
Reply
Cancel
0 on May 1, 2017

^what Job said. Generally you would set it in the Start method. I don’t know if it’s a great way, but I tend to use tags to find game objects. Just create a tag for what you want to find and make sure to assign it to the gameobject your text.

void Start{
funnyBunny = GameObject.FindGameObjectsWithTag(enter your tag here(as a string));
}

FindGameObjectsWithTag Docs

  • Liked by
Reply
Cancel