I’m making a game where you can design a highly customizable castle.
Because internal walls, floors, windows, etc. are constantly shifting and stretching as player tweaks the parameters, I have an elaborate hierarchy of game objects, the leaf level often containing a single quad or triangle. A segment of castle (ie a tower or short stretch of wall) would contain about a thousand GameObjects.
So far the game works great!
The only problem is that instantiating all of those game objects takes time.
Generating a single tower takes about 3 seconds during which the screen freezes.
But I want the player to be able to place segments just like: “click, click, click”.
How should I optimize my game?
Some ideas I had were:
- Generating the castle by adding vertices and faces to a single mesh and then update the mesh by holding references the vertices which can be translated. (This would be fine for allot of stuff… but my existing system rotates chunks of wall into position around a central pivot point provided by the gameobject hierarchy. Trying to place verts without the parenting or rotation systems provided by GameObjects would require an insane amount of geometric calculations on each individual vert making the code incomprehensible.)
- Instantly placing some crude approximation of a segment of castle when the player clicks, while secretly instantiating a hierarchy of game objects behind the scenes ready to replace the temporary gameobject as soon as possible. (I have no idea how to multi-thread or whether the Unity API would even allow you to instantiate game objects on a separate thread.)
- The “aproximation” mentioned in point 2 could be accomplished by merging the entire segment into one mesh so that it could be saved. This singular mesh can then be instantiated as one gameobject when ever it needs to be duplicated quickly.
- I could use a combination of these ideas if I keep the Gameobject hierarchy approach but generat Quads in code rather than instantiating prefabs of quads.
My arising questions are:
- Is creating a mesh in code faster or slower than instantiating the same geometry from a prefab?
- Can you Multithread Unity and instantiate Gameobjects secretly without creating an unresponsive state for the player?
- Is there an easy way to merge all the meshes of a game objects children into one mesh while retaining their relative positioning?
- Are there any statistics on how long(processing) a GameObject takes to instantiate?
- Do you know of a better way to do this?