FICHEKK
FICHEKK

Reputation: 819

How to switch GameObjects without Instantiate and Destroy?

I am creating an infinite 2d terrain generator and it has all kinds of tiles/blocks in it. Also, some tiles have special functionalities that are described in their own scripts.

For example, a beehive tile can spawn bees around it. Dirt tile can turn into grass if there is grass nearby, etc.

Now, all these tiles are almost the same GameObjects, except the only difference between is what sprite they use (icon) and a script that describes their behaviour.

Now I could easily make a prefab of all the tiles and Instantiate the prefab when I load new terrain and Destroy the prefab when it gets unloaded, but that surely would not be a good idea for garbage collector since these tiles get spawned in orders of 100s in seconds.

Also, object pooling is NOT an option here because there are too many objects I would need to create at start (10s of thousands).


So, this is my problem:

I have a dirt tile which has Dirt script on it. Once some time passed, I would want to convert it into grass tile which has Grass script component, but not Dirt.

Is there any better way of converting those GameObjects other than removing Dirt script and adding Grass script? Also, how efficient is adding and removing components in large amounts?

Upvotes: 1

Views: 116

Answers (2)

Moons
Moons

Reputation: 623

You can make a parent gameobject that holds different type of tiles. Then activate/deactivate childs as needed.
Your hierarchy would look like this:

Tile (Holds switching functionality)
 |->Dirt Tile (Holds 'Dirt' functionality)
 |->Grass Tile (Holds 'Grass' functionality)
 |->Water Tile (Holds 'Water' functionality)
 |-> ...

For example, When you want the tile to be Dirt, You activate Dirt Tile gameobject under Tile and deactivate all other children.

Let me know if it was helpful or not.

Upvotes: 1

Loghman
Loghman

Reputation: 1499

You said pooling is not an option, but I suggest using lazy loading to create the object for the pool. you create those for the first appearance which won't need much time and in progress, you create more if needed.

Upvotes: 3

Related Questions