Lag in creation of new object

I’m making a clicker game similar to clicker heroes where you click until you kill a monster then it dies you get money then a new one spawns.

The problem I’m having is there is a long delay when it dies to when the new one is created.

Here is how I’m currently doing it. On the death animation I have the following script running.

   override public void OnStateExit(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
    {
        //animator.gameObject.transform.position= new Vector2(10000,10000);
        Destroy(animator.gameObject);
    }

Then in my GameManager I have

    private void Update()
    {
        if(enemyClicking==null)
                {
            GameManager.instance.AddMoney(enemyClicking.enemy.goldValue);
            PickEnemy();
        }
       
    }

PickEnemy chooses a random enemy and sets it up. I’ve tried moving the destroy to a different area but then the death animation doesn’t complete first. Right now there is a delay after the death animation by about a half second before the next enemy appears.

Any ideas what I should look for to fix it or what might be causing this would be great. If there are any other questions on what I did in the different areas of code I can also put that in here if it helps but everything else seems to be working and I think it has something to do with these places.

Google “Object Pooling”. If you regularly create and destroy objects of the same kind, Object Pooling is a must. There are many existing systems/tutorials or you can roll your own, but essentially, instead of instantiating and destroying, you just activate and deactivate them, usually with some code to reset the object to the initial state.

1 Like

I’ve done object pooling before but figured since it’s a single object I wouldn’t need to. I’ll rewrite to use pooling and see if that was the problem.

The quantity doesn’t matter, it’s how often the thing is spawned and destroyed.

1 Like

Put a Debug.Log("final call!"); call right next to the Destroy().

I predict you will find that nothing is lagging and that the state just does not end when you think it does but rather gets called much later.

If this is the case, fix it in the Animator / Animation(s).