Search Unity

Resolved Attribute on static method for unity life cycle hook

Discussion in 'Scripting Dev Blitz Day 2023 - Q&A' started by Thaina, Feb 23, 2023.

  1. Thaina

    Thaina

    Joined:
    Jul 13, 2012
    Posts:
    1,168
    Attribute are more convenient for lifecycle listener than event/delegate

    I want to propose

    [EditorUpdateMethodAttribute]
    [RuntimeUpdateMethodAttribute]
    [RuntimeFixedUpdateMethodAttribute]

    for static method global update

    [BeforeSceneLoad]
    [AfterSceneLoad]
    [BeforeSceneUnLoad]
    [AfterSceneUnLoad]
    [ActiveSceneChanged]

    for static method related to scene
     
  2. Maria_Angelova

    Maria_Angelova

    Unity Technologies

    Joined:
    Mar 3, 2020
    Posts:
    29
    I can see how these can make it less cumbersome to hook up functionality in some cases.
    For editor lifecycle events, eg. scene load/unload/change these make a lot of sense and a potential implementation would not cause any issues. However having both events and attributes may make it confusing and hard to reason about order of execution so more APIs covering the same goal is not always a good thing. We could move in a direction of replacing existing Unity events with attribute-marked callbacks, however those are generally static in nature thus not always desirable.
    To enable attributes like these for the player we would need a missing feature - TypeCache-like functionality for the player - in order for discovering these to be feasible performance-wise.
    Player loop also involves many different stages, which can nest into each other and can be scripted. Thus the natural thing would be to allow hooking up in any point inside the player loop, so the attributes would be nice to be more generic in nature.
    Thank you for the suggestion. We will take these into consideration when evolving our lifecycle APIs.
     
    mariandev, TeodorVecerdi and Thaina like this.
  3. Thaina

    Thaina

    Joined:
    Jul 13, 2012
    Posts:
    1,168
    I could say most case we want to hook up functionality for the whole game. And when there is a logic that not really for the whole game or whole lifecycle, it most likely a known task that could be handled by async method or reactivex library

    About order of execution, I think we could have operation order API. Any more complicate than that then it should be gameobject or ECS system

    Maybe there could be [Runtime{Before/After}Update] or something like that