Search Unity

Weird lag

Discussion in 'Scripting' started by ScottyRich, Jun 23, 2014.

  1. ScottyRich

    ScottyRich

    Joined:
    Oct 7, 2013
    Posts:
    35
    I'm making a 2d game where the player is introduced by falling down from the sky, and then the player object is instantiated through code. It always took a lot of unexplained CPU space. over 30%. I thought that was what made the game run slow. But when I put the player in from the beginning, in addition to the one that hasn't spawn. CPU space was just as high, but the game ran literally over twice the speed. Hey, it's great that it fixed the lag, but the player has to fall down from the sky. Why would adding an additional character object double the speed of the game?
     
  2. smitchell

    smitchell

    Joined:
    Mar 12, 2012
    Posts:
    702
    Instantiate is a well known performance flaw, look into object pooling, that's a nicer way to create objects without affecting performance too much
     
  3. ScottyRich

    ScottyRich

    Joined:
    Oct 7, 2013
    Posts:
    35
    That's what I thought, but the weird thing is, it's still instantiating. At the beginning, there's already a player, and then a second player is instantiated. The speed is doubled. I can't find logic in it.
     
  4. smitchell

    smitchell

    Joined:
    Mar 12, 2012
    Posts:
    702
    yeah it does still instantiate, but because it's at the beginning the player can't really tell that there was any lag, you'd build it into your loading, etc. So then when you do need to create something you just reuse it from the pool
     
  5. ScottyRich

    ScottyRich

    Joined:
    Oct 7, 2013
    Posts:
    35
    Okay, I never tried the pool, but by trial and error I figured out that somehow, the fact that many objects were using GameObject.Find("_Player") and that not instantiated version of _Player being there since the beginning eliminated the lag. So instead of instantiated, I just made the not instantiated _Player paused and unrendered until the point where it would have been instantiated. Tada! No lag. It's not a good practice, but it works. :D
     
  6. smitchell

    smitchell

    Joined:
    Mar 12, 2012
    Posts:
    702
    Yeah GameObject.Find() is also quite slow, Unless you actually really need it try to cache variables as much as possible to save performance