Room randomization

hey, my game needs randomness. ive made the rooms randomly spawn when you go thro a door but i dont know how to destroy the last one after you go to a new one plz can you help?

Video

Code

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Doors : MonoBehaviour
{
    public GameObject[] Rooms;
    [Space]
    [Space]
    public Transform player;

    public Animator fade;

    public Transform RoomPos;

    public Vector3 SpawnPos;
  
    void OnCollisionEnter2D(Collision2D other)
    {
        
        if (other.gameObject.CompareTag("Door"))
        {
            fade.SetTrigger("Fade");

            Invoke("ChangePos", 0.5f);

            player.position = new Vector3(0f, 0f, 0f);


        }

         
    }

public void ChangePos()
{

    Instantiate(Rooms[Random.Range(0, Rooms.Length)], RoomPos.position, RoomPos.rotation);
}

oh i just realized i can add the script to the prefabs to destroy themselves when you enter a door

–

1 Answer

1

@joshbowden42
That should work. If you have any question I’ll respond to you tomorrow.

public class Doors : MonoBehaviour
{
    public GameObject[] Rooms;
    [Space]
    [Space]
    public Transform player;

    public Animator fade;

    private GameObject currentRoom;

    private GameObject newObject;

    public Transform roomSpawnPosition;


    void Start()
    {
        currentRoom = Instantiate(Rooms[Random.Range(0, Rooms.Length)], roomSpawnPosition.position, roomSpawnPosition.rotation);

    }

    void OnCollisionEnter2D(Collision2D other)
    {

        if (other.gameObject.CompareTag("Door"))
        {
            fade.SetTrigger("Fade");

            Invoke("ChangePos", 0.5f);

            player.position = new Vector3(0f, 0f, 0f);


        }


    }

    public void ChangePos()
    {
        newObject = Instantiate(Rooms[Random.Range(0, Rooms.Length)], roomSpawnPosition.position, roomSpawnPosition.rotation);
        if (currentRoom != null)
        {
            Destoy(currentRoom);
        }
        currentRoom = newObject;
    }
}