I am firing bullets using raycasts and I am placing bullet holes consisting of planes with decals on them at the hit point of the raycast.
To avoid instantiating GameObjects during gameplay, I created a simple object pool. My ObjectPool class has an instantiateBulletHoles function that I call from from my gun script on Awake() that creates a specified number of bulletHole GameObjects and puts them in an ArrayList
This seems to work fine, my bulletHole game objects are created as soon as I start the game. Then, in my OnHit function in my gun script which fires when my raycast hits something, I call the getBulletHole function of my ObjectPool, which takes the next bullet hole in my ArrayList and places it at the hit point. If there are no more available bullets, it loops back around and recycles the first bullet hole in the list.
The problem is that when I start firing I get a split second freeze lag. If I continue firing after that it keeps placing bullet holes smoothly, but if I stop firing for a few seconds and then start again, it freezes again. This happens both on my Android device and on my six core, 12gb RAM workstation (framerate drops from 600+ towards zero).
Does anyone have any thoughts on what might be causing this lag? Any pointers to what can be improved in this code is greatly appreciated.
Not sure if these are the causes of your problems, but here are a few ways you could possibly improve this code:
1) Since you know precisely the number of bullets you need to cache and that value never changes, it might be more efficient to use a built-in array to hold the bullets, like
2) As you are instantiating bullet holes, you can call gameObject.active = false to deactivate the bullets. Then, you just activate them as they are needed and then deactivate them when they hit their "fade out" time. If your bullets have children, you can use SetActiveRecursively to accomplish this as well.
You may have already tried this, but also take the bullet hole code out of the gun and see if you still get the issue - it could be something other than the bullet holes that cause the gun to seize up while firing.
answered May 06, 2011 at 05:14 PM
thanks! this has helped me solve my problem. Actually i had used a print(); to output a number while my bullets get shot. this has caused a lag. thanks!
answered May 10, 2011 at 05:58 PM