I’m working on doing procedural level generation using unity tilemaps and I’m having an issue getting the instantiated rooms to unparent from the spawner and parent to the grid. I have tried several different approaches with zero luck. Ideally the spawned rooms will be locked in the position they are spawned and parented to the grid but currently no matter what I do they stack on top of each other and move with the spawner.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LevelGeneration : MonoBehaviour
{
//changing for tilemap
private GameObject grid;
public Transform[] startingPositions;
public GameObject[] rooms;
private int direction;
public float moveAmountX;
public float moveAmountY;
private float timeBtwnRoom;
public float startTimeBtwRoom = 0.25f;
private void Start()
{
//tilemap integration
grid = GameObject.FindGameObjectWithTag("Grid");
int randStartingPos = Random.Range(0, startingPositions.Length);
transform.position = startingPositions[randStartingPos].position;
GameObject newRoom = Instantiate(rooms[0], transform.position, Quaternion.identity);
newRoom.transform.parent = null;
newRoom.transform.SetParent(grid.transform);
direction = Random.Range(1, 6);
}
private void Update()
{
if (timeBtwnRoom <= 0)
{
Move();
timeBtwnRoom = startTimeBtwRoom;
}
else
{
timeBtwnRoom -= Time.deltaTime;
}
}
private void Move()
{
if (direction ==1 || direction == 2)
{
//Move Right
Vector2 newPos = new Vector2(transform.position.x + moveAmountX, transform.position.y);
transform.position = newPos;
} else if (direction == 3 || direction == 4)
{
//Move Left
Vector2 newPos = new Vector2(transform.position.x - moveAmountX, transform.position.y);
transform.position = newPos;
} else if (direction == 5)
{
//Move Down
Vector2 newPos = new Vector2(transform.position.x, transform.position.y - moveAmountY);
transform.position = newPos;
}
GameObject newRoom = Instantiate(rooms[0]) as GameObject;
newRoom.transform.position = transform.position;
newRoom.transform.SetParent(grid.transform);
direction = Random.Range(1, 6);
}
}
There are two different approaches used in my code and I have tried many others as well and no matter what I’ve tried rooms parent to spawner. The first room spawns on lines 29-31 and the rest spawn from the code on lines 68-71. Really pulling my hair out on this one. If anyone has any insight on this it would be greatly appreciated.