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.

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"; 
	}
}

track.gameObject.name = “name”;

respect the case ++

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 :slight_smile:

Works if you call it a GameObject