- Home /
problems parenting a gameObject to another upon instantiating when same name exists
Hi all, I am having trouble getting my code to automatically parent objects when instantiated.
Basically, my levels are all generated through code. It automatically generates empty gameobjects for the levels and the rooms in each level, then parents objects upon instantiating them to the correct places.
Ex:
Level1 > Room1 > LevelTile1
Level2 > Room1 > LevelTile1
Level3 > Room1 > LevelTile1
Level4 > Room1 > LevelTile1
However, despite everything working fine, my tiles are all appearing under Room1 in level1, thats because I have no way (yet) to work out which levels the rooms are under.
Here are some code snippets of how its working:
First create the Level
emptyObject = new GameObject("Level" + tempLevelNumber);
GameObject currentLevel = GameObject.Find("Level" + tempLevelNumber);
Then create the room and parent to the level
emptyObject = new GameObject("Room" + tempRoomNumber);
emptyObject.transform.parent = currentLevel.transform;
Then create tiles and parent to the room
GameObject currentRoom = GameObject.Find("Room" + tempRoomNumber);
GameObject LeftEnd = Instantiate(levelEndLeft[Random.Range(0, levelEndLeft.Length)], levelStartPoint, transform.rotation) as GameObject;
LeftEnd.transform.parent = currentRoom.transform;
And here is where it goes wrong, as I create in level 2, 3, 4 etc. they are all parenting to Rooms under level 1 as I cannot seperate out which rooms are under which level!
ie. All tiles for each room are under level 1, and all the other rooms in the further levels have no children as it finds them first in level 1.
I hope that all makes sense!! Any ideas?
Sorry I should have said the the heirachy creates just fine, I all levels and all rooms are present, its just that all the tiles are children of the rooms in level 1 only, as I cant define which level the room is under when parenting a tile
Answer by NerdRageStudios · Feb 27, 2015 at 10:42 PM
Found my own solution using strings to create the full path for GameObject.Find
GameObject currentRoom = GameObject.Find("Room" + tempRoomNumber);
string stringLevel = ""+currentLevel.gameObject.name;
string stringRoom = "/" + currentRoom.gameObject.name;
string stringFullPath = stringLevel + stringRoom;
GameObject currentRoomInLevel = GameObject.Find(stringFullPath);
Your answer
Follow this Question
Related Questions
Creating new Transform from existing objects Transform to Instantiate object 1 Answer
Why does this Instantiate give a Null Reference Exception? 1 Answer
Instantiate as a child at position 2 Answers
Create a Transform without a GameObject 2 Answers
Controlling the update position of a cloned Gameobject C# 1 Answer