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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Launching script without attaching to game object

Discussion in 'Scripting' started by DoomDude99, Mar 4, 2020.

  1. DoomDude99

    DoomDude99

    Joined:
    May 11, 2019
    Posts:
    87
    Can scripts be launched without being attached to a game object? or should there always be an empty object
    present?
     
  2. Olmi

    Olmi

    Joined:
    Nov 29, 2012
    Posts:
    1,553
    Hi @DoomDude99,

    Methods marked [RuntimeInitializeOnLoadMethod] get invoked after game is started. These can be in any script folder, there's nothing required to reference them in the scene, like a Monobehaviour class (afaik.)
    See docs: https://docs.unity3d.com/ScriptReference/RuntimeInitializeOnLoadMethodAttribute.html

    And you can run instances of classes that are not inherited from Monobehaviour, just create them by using new MyClassName and so on? But you need some Monobehaviour script in your scene where you do that.
     
    Marks4 and DoomDude99 like this.
  3. DoomDude99

    DoomDude99

    Joined:
    May 11, 2019
    Posts:
    87
    Thx :)
     
  4. holo-aidan

    holo-aidan

    Joined:
    Aug 4, 2021
    Posts:
    5
    This is great for starting a script after the game starts but is there a way to listen for the game ending in order to carry out clean-up? It seems the scripts destructor is not always called right as the game end and sometimes instead as the game mode is re-entered (in the editor anyway).
     
    AndrewSerrow likes this.