Hi everyone! I've got a question today about game optimization. (my actual least favorite thing)
I want the demo I'm working on to run well on lower-end machines. Not too low-end, but I'd love if it could run smoothly on the average laptop. It runs well as is on my desktop computer, but it hits soem pretty abysmal lag spikes on my laptop. I've deduced the culprit in the visual profiler to be Render 3D Transparent Pass, Render Opaque Pass, and Tonemap, all under Render 3D Scene.
It doesn't look too bad in the image, but it's way worse on my laptop. Essentially, it seems like my game is spending a lot of time behind the scenes with rendering, and I think I might know why.
There are a lot of objects in my game; an essential game mechanic is the way they rain down from the sky for you to collect them. The same goes for the enemies of the game, though there are vastly fewer of those active at any time. I accomplish this by instantiating the scene for the item (which is a CharacterBody3D), randomizing its spawn position, then adding it is a child in the sky, upon which its own coding takes care of the rest; It will fall down and be deleted (queue_free) when the player either collects it or it has been sitting for too long. Here's what the script in my "world" scene that spawns items looks like:
func _on_item_timer_timeout(): #this makes the code run every time an item timer runs out. spawns one item after another every .07 sec
if Autoscript.trashnum < 250: #places a hard limit on how many items can exist at once.
randomize()
var item = item_scene.instantiate() #instantiates the item scene
var spawnX = randf_range(-200.0, 200.0)
var spawnZ = randf_range(-200.0, 200.0)
item.transform.origin = Vector3(spawnX, 30.0, spawnZ) #moves the item to a random position determined by the previous vars
add_child(item) #creates a new item
Autoscript.trashnum += 1 #enables the cap on items above to work. goes down when an item is taken out of play
Now, even my cursory knowledge of game optimization says this is not a good way of doing things. Constantly creatingand deleting objects, as I'm told, takes a toll on the processor and is generally not best-practice. I know that a much better way of doing things would be to spawn a set 250 or so items at the start of the game and move them as needed. The issue is, I have no idea how to actually do that. Does anybody have a good method of making all those objects and moving them each as they need to be? Or am I going about this the wrong way entirely? Is there an even better way of doing this that I haven't considered? Please let me know if you can help or need more information! Thank you!!