Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Voting for the Unity Awards are OPEN! We’re looking to celebrate creators across games, industry, film, and many more categories. Cast your vote now for all categories
    Dismiss Notice
  3. Dismiss Notice

Adding "Lazy Start()" function

Discussion in 'Scripting' started by joshcamas, Jul 1, 2018.

  1. joshcamas

    joshcamas

    Joined:
    Jun 16, 2017
    Posts:
    1,268
    Hello friends!

    So I know that adding awake and start functions to my monobehaviors slows down the game a lot since it has to run all of that junk when a scene runs. I'm assuming this is what is causing my game to freeze so badly.

    SO! What if instead I made a sort of "Lazy Start"? Basically the game will get a list of all the objects that have this function, then disperse the running of these functions over several frames.

    The issue is: How do I tell the engine what objects have this lazy start function? My only idea is upon Start() add the instance to the list, but of course that defeats the purpose of having Start().

    In fact, how does the engine know what objects have a Start() or Awake() function at all? It's not a override...

    Any thoughts?

    Josh
     
  2. lordofduct

    lordofduct

    Joined:
    Oct 3, 2011
    Posts:
    8,378
    Start and Awake have some overhead... but really not much. Nearly all of my scripts use Start and Awake to do stuff and we don't have any huge performance issues as a result. These 2 functions are only really ever called once in the lifetime of the script...

    Are you doing something really intense in the 'Start' method that could cause slow down? Performing blocking type actions that take a long time?

    All your doing though is moving the operation to another frame. Do you have a problem of constantly spawning lots of new objects in a single frame? Because if you're just moving a handful of 'start' calls... changing when they're called won't really speed anything up.

    Interfaces would work for this. Define an interface with a 'LazyStart' method defined. If you want to have a LazyStart you just implement the interface, and you know if it has a LazyStart by checking if it 'is' a lazy start type object with the 'is' operator.

    The engine uses reflection to figure out what messages each script has defined.

    Use the profiler!

    Find out what is actually slowing your game down.

    I doubt it's just the existence of 'start' methods.