How do I gain access to objects in order to change their properties in Unity?

I have created a GUI text object named "GUIText" in the Unity editor, and I want to change what the text says via code (I'm using C#). How do I access GUIText1 to change its string properties?

I want to be able to write code like this:

GUIText1.Text = "";


In general, I'm not sure how to get access to any sort of object created in the editor (a mesh or a light for example). How do you access them in code?

I already know how to write the scripts and trigger them.

Considering GUI Text is a component of a gameobject in your scene, you can do this:

In the script where you want to make the change, you add a public field of type GameObject, like so:

public GameObject someObject;


Make sure the script inherits from MonoBehavior; you have to add the script as a component to some game object of your choosing. For example, create an empty gameobject somewhere, and add the script to it. If you've done everything correctly, you should be able to set the reference to the gameobject that contains the GUI Text component via the visual editor (just click on the gameobject that contains the script with the public GameObject field).

Next, in the Start() method of the script you write:

GUIText guitext1 = someObject.GetComponent<GUIText>();
//Do something with guitext11 e.g. guitext1.Text = "";


Alternatively, you could use a GUIText reference instead of a GameObject one; referencing it via the editor should work the same, though by doing it the way I wrote above you also get to know how to manually access a particular component of a GameObject.

In case you get stuck:

class MyScript : MonoBehavior
{
public GameObject someObject; //You set this with the editor.

private void Start()
{
GUIText txt = someObject.GetComponent<GUIText>();
txt.Text = "";
}
}