- Home /
How can I instantiate object and give it a name?
This is what my code currently looks like:
public Transform Rail;
public GameObject structPoint;
// several lines later
GameObject track = (GameObject)Instantiate(Rail, new Vector3(structPoint.transform.position.x, structPoint.transform.position.y, structPoint.transform.position.z), Quaternion.identity);
track.name = "track1";
I'm not sure why it gives me an error.
Answer by robertbu · Mar 16, 2014 at 06:59 PM
Your 'several lines later' probably hides the problem. You need to execute your Instantiate() inside a function. Something like:
using UnityEngine;
using System.Collections;
public class Example : MonoBehaviour
{
public Transform Rail;
public GameObject structPoint;
GameObject track;
void Start() {
track = (GameObject)Instantiate(Rail, new Vector3(structPoint.transform.position.x, structPoint.transform.position.y, structPoint.transform.position.z), Quaternion.identity);
track.name = "track1";
}
}
You are missing a set of brackets:
void Update () {
if(Input.Get$$anonymous$$ey($$anonymous$$eyCode.$$anonymous$$)) {
GameObject track = (GameObject)Instantiate(Rail, new Vector3(structPoint.transform.position.x, structPoint.transform.position.y, structPoint.transform.position.z), Quaternion.identity);
track.name = "track1";
}
}
Thanks, it works. Unity was glitching so the code didn't work until I restarted Unity.
Unfortunately by the time the track.name="track1"; gets executed, the Awake function on the instantiated object has already been called. So anything in there that needs unique names is screwed. One of the stupid architecture designs in Unity.. And no, just moving the code from Awake to Start is not the answer.
Answer by sami1592 · Mar 16, 2014 at 07:03 PM
you have to instantiate a prefab that you have to declare as GameObject, not a Transform
public GameObject Rail; // GameObject, not Transformer
public GameObject structPoint;
// several lines later
// remove the (GameObject)
GameObject track = Instantiate(Rail, new Vector3(structPoint.transform.position.x, structPoint.transform.position.y, structPoint.transform.position.z), Quaternion.identity);
// track.name = "track1";
// try this
track.gameobject.name = "track1"
Lets hope it works :)
Edit: Never$$anonymous$$d, it works but the instantiated objects are not being renamed.
Your answer
Follow this Question
Related Questions
Distribute terrain in zones 3 Answers
Multiple Cars not working 1 Answer
Spawning a prefab at another object's location 3 Answers