Unity - Lag happen only when i first intantiate an object

Viewed 70

So i have a detection script that look like this:

IEnumerator Detect()
    {
        while (true)
        {
            var collision = Physics2D.OverlapCircle(transform.position, radius, layerMask);

            if (collision != null)
            {
                var obj = collision.GetComponent<IDetectionObject>();

                if (lastDetectedObject != obj)
                {
                    obj.Ping();
                    lastDetectedObject = obj;
                }
            }

            yield return new WaitForSeconds(interval);
        }
    }

And this script will trigger (ping) a dialogue banter, and will deliver the banter to the player. and player will run this code:

public void Say(string banter, float duration)
{
    currentBubble = bubbleManager.GetBubble();

    currentBubble.SetText(banter);
    currentBubble.BindToTransform(transform, () => currentBubble = null);
    currentBubble.SetDuration(duration);
}

The BubbleManager.cs Script using a PoolObject from unity, this is the code:

private void Awake()
{
    bubblePool = new ObjectPool<BanterBubble>(() =>
    {
        return Instantiate(bubblePrefab, transform);
    }, bubble =>
    {
        bubble.gameObject.SetActive(true);
    }, bubble =>
    {
        bubble.gameObject.SetActive(false);
    }, bubble =>
    {
        Destroy(bubble);
    }, false, 10, 20);
}

public BanterBubble GetBubble()
{
    var bubble = bubblePool.Get();
    bubble.Init(this);
    return bubble;
}

public void ReleaseBubble(BanterBubble bubble)
{
    bubblePool.Release(bubble);
}

Okay, now here is the problem. Whenever i test play my game, and when player detect IDetectionObject interface, its always lag. but only for the first time.

and after that the game will run smoothly, even though i trigger so many IDetectionObjects. the lag is pretty bad so i really want to clear this problem.

What I Already Done

  • Use Instantiate() instead of Get Object from PoolObject which is BubbleManager, the lag still happen on the first time. after that always smooth.
  • Build the game and play. And yes.. the lag still happen in build game.
  • Use Debug. and yes the lag is gone. so i think the problem is with how i instantiate my object

What I Suspect

  • The Bubble is a UI object, so it must use a canvas to render, maybe instantiating a canvas object is heavy?
  • Maybe My Unity Version is not stable ? I use Unity 2022.1.10f1
1 Answers

When an element changed in canvas, the whole canvas rebuild.

"Many users build their entire game’s UI on a single Canvas with thousands of elements. When they change one element, they can experience a CPU spike costing multiple milliseconds" from unity docs.

Related