- Home /
Placing object based on child relative to another gameObject.
The title is pretty confusing. Basically, this is what I want to do:
I am creating a handful of rooms from room prefabs that I have already made.
The room has an empty gameobject on the left and a door on the right.
The room's position is placed so that the empty gameobject is in the same position as the previous room's right door.
Here's what I have so far that works:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LevelCreator : MonoBehaviour
{
public GameObject[] rooms;
[Tooltip("The number of rooms to create")]
[Range(1, 20)]
public int numberOfRooms = 10;
private float xPos = 0;
private float distBetweenDoors = 0;
private Vector3 pos;
public void Start()
{
for (int i = 1; i <= numberOfRooms; i++)
{
GameObject room = Instantiate(rooms[Random.Range(0, rooms.Length)], pos, transform.rotation);
Transform leftDoor = null;
Transform rightDoor = null;
for (int child = 0; child < room.transform.childCount; child++)
{
if (room.transform.GetChild(child).gameObject.tag == "Door/LeftDoorPos")
{
leftDoor = room.transform.GetChild(child).transform;
}
if (room.transform.GetChild(child).gameObject.tag == "Door/RightDoor")
{
rightDoor = room.transform.GetChild(child).transform;
}
}
if (leftDoor != null && rightDoor != null)
{
print("Found both doors!");
//This works fine if all rooms are the same size, but not if they aren't
distBetweenDoors = Mathf.Abs(rightDoor.position.x - leftDoor.position.x);
print(distBetweenDoors);
xPos += distBetweenDoors;
}
pos = new Vector3(xPos, 0, 0);
}
}
}
Here's what this currently makes:
Here's what I want it to make:
Thanks in advance for any help.
Answer by CmdrZin · Dec 17, 2020 at 08:17 PM
Use the center of the room for your calculations and find the Xoffset for each door or make the offset from center the same for left and right doors.
So if RoomA length = 10 and center at 30. RoomA Left door child is at 25 and Right door is at 35.
RoomB length = 16. With Left door offset of 8 and Right with 8. RoomB position is then RoomA Right door pos + RoomB Left door offset or 35 + 8 = 43.