- Home /
Naming Instantiated Prefabs
Hi,
In my game, I'm trying to make it so that a new room spawns every time you open a door. I got that working, however, keeping track of the rooms can be annoying and can cause issues further down the line if the naming is automatic since it just calls it "Room_Prefab(Clone)" and keeps adding "(Clone)" to the name of every room after. I want to be able to name these specifically on every instantiation.
I almost got that working, however, it doesn't work like I want it to. The way I have it working right now makes the room rename itself before it spawns another room (Which is unaffected by the name change code). I'm not exactly sure how to name the new instantiated room. Here's my code that controls the instantiation. Any ideas?
void Update ()
{
if (door.open && !door.spawnOnce) {
// create the new room:
roomNum++;
Instantiate (Room_Prefab, transform.position, transform.rotation);
Room_Prefab.name = Room + roomNum;
door.spawnOnce = true; // make sure it's created only once
Debug.Log("New Room!");
Debug.Log(roomNum);
}
Answer by LukaKotar · Oct 18, 2013 at 02:54 AM
The way you are doing it now, will try to rename the prefab itself. You might want to store the instantiated room instance as a variable:
Transform roomInstance = Instantiate (Room_Prefab, transform.position, transform.rotation);
roomInstance.name = "Your desired name";
roomInstance = null;
Adding to that, I'm a big fan of creating a root-level GameObject which can contain all of those spawned instances. After spawning each instance, I set its transform.parent
to the root object. Anything that keeps the scene tidy is helpful.
Answer by Arunneupane · Aug 13, 2017 at 05:13 PM
@SuperSparkplug @LukaKotar using System.Collections; using System.Collections.Generic; using UnityEngine;
public class spawn : MonoBehaviour { public GameObject cube;
void sp() // function to spawn
{
Instantiate(cube, new Vector3(1.52f, -7.962671f, 11.86f), transform.rotation);
int num =+ 4; // declaring value of num and it gets updated and increased by 1
num++;
cube.name = "cube" + num; //adding into its name
}
// Use this for initialization
void Start () {
InvokeRepeating("sp", 10f, 10f); // inorder to spawn objects
}
}