Unity 2D Instaniate prefab with text

c#, unity-game-engine

Solution

AD1: It's `GameObject.Instantiate`:

var go=GameObject.Instantiate(prefab, Vector3.zero, Quaternion.Identity) as GameObject;

A prefab is an asset-like GameObject that is used as a template for scene GameObjects.

To use a prefab you have to drag a GameObject to the project window and reference it in code in one of two ways:

Using resources, `var prefab=Resources.Load("my-prefab")` will load the project file `Resources/my-prefab`. Note the use of the special "Resources" directory - it's a magic name that is required.

Using a reference, in a `MonoBehaviour` add a `public GameObject prefab` field. Then on a GameObject using this class you can drag and drop your prefab from the project window to create a reference to it. You can then use the `prefab` field in your code. No "Resources" directory needed here.

Prefer option 2, as all resources are in the final binary, while normal assets are trimmed when possible.

AD2: get the `TextMesh` compontent and modify `text`:

go.GetComponent<TextMesh>().text="new text";

Problem

I'm new to Unity3D and looking for some basic information. I'm used to OO programming, but I cannot quite see how to access the objects from script. I created an object, made it a prefab (plan on using it many times) and the object has text on it. The text uses a Text Mesh. I'm using C#. - How do I thru code, simple example on start, instantiate a new prefab object called Tile at 0,0? - How do you access the text Mesh part of the object to change the text? I sure there is something simple I'm not picking up on. Just having trouble understanding how to connect the code to the objects and vice versa. Updated: Also wanted to note, I'm trying to load multiple objects at the start, if that makes a difference in the answers. Update2: Just wanted to explain a little more what info I was missing when tying the mono code to the unity interface. In Unity: Created any object and turn it into a prefab. Created a second empty game object, place it somewhere in the play view area. Created a script on the Empty game object. In Mono code editor: Created 2 public variables (C#) ``` public GameObject spawnObj; public GameObject spawnPoint; void Update () { Instantiate (this.spawnObj, this.spawnPoint.transform.position, this.spawnPoint.transform.rotation); } ``` Back in Unity: Select the Empty Game Object. In the script Component, you should see the 2 vars. Drag your Prefab Object into the var spawnObj. Drag the Empty game object into the var spawnPoint. I did this is the Update, not to smart, but it spawned a cube or 2 or more, spawning from code is all I wanted to understand.

Original source