Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Generating/Deleting Vs Moving/Hiding Prefabs

Discussion in 'Scripting' started by ivanger08, Feb 19, 2021.

  1. ivanger08

    ivanger08

    Joined:
    Jan 27, 2021
    Posts:
    10
    Hi im working on an endless obstacle game, my ground is a 400 long and is continous telestransporting every time player reach 200 distance units, what is the best practice for placing obstacles forever?
    upload_2021-2-19_15-40-24.png
    Giving a difficulty pattern generation, the game will be placing obstacles, I have 2 ideas of how I can archive that goal:
    1. Creating new Prefabs and deleting them via script
    2. Create an amount of prefabs in the Unity Editor that covers the maximum possible obstacles that will ever appear in the game and Moving and Hiding them via script
    upload_2021-2-19_16-2-2.png
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,336
    Either way is a valid approach. Plenty of games out there using either method. Each has pros and cons. I'd just pick one and try it, see how it goes. It is SOFT-ware after all, so it is SOFT and can be changed. :)
     
  3. Lekret

    Lekret

    Joined:
    Sep 10, 2020
    Posts:
    272
    AFAIK instantiating is relativly bad for performance. So I would rather read about Object Pool pattern or watched the video, and made one.

    It's pretty easy, you basically have an abstraction called ObjectPool with Queue<Obstacle>. If pool has disabled object which is ready for reuse, pool returns it, if not, then pool instantitates a new one and put it to the end of the Queue. Or you can instantiate 20-30 obstacles in the Awake method, which is ok too.

    Then you just inherit your Spawner from ObjectPool and pool from MonoBehaviour, or use composition and keep Pool as a field. Simple and optimized.
     
    ivanger08 likes this.
  4. seejayjames

    seejayjames

    Joined:
    Jan 28, 2013
    Posts:
    685
    How about the maximum number of obstacles the player will ever see at once? The second they go past the player, they're eligible for transporting ahead. You'd only need a handful, spawn them all at the beginning and re-use. Particularly if they're simple shapes, Unity can handle huge numbers of them, so you're totally fine.
     
  5. ivanger08

    ivanger08

    Joined:
    Jan 27, 2021
    Posts:
    10
    I did your suggestiot and It worked, thanks!
     
    Lekret likes this.