Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
1
Question by rtm223 · Apr 13, 2017 at 12:43 PM · editor-scriptinginitialization

[InitializeOnLoad] for editor load only

Hi all,

I've been trying to use [InitializeOnLoad] attribute, to run some code when the editor launches. However, I'm finding two main issues: 1. The static class is constructed twice (seems to be a known issue) 2. The static class is constructed when I hit Run, which seems to be by design.

I can't find any way to ignore the second construction on editor launch, which might not be an issue.

More importantly I cannot find a way to ignore the construction when hitting Run I have tried testing for Application.isPlaying, but this returns false, as I assume we're running very early in the initialization. According to the API, "when Run is pressed ... the Unity runtime is intialised and this is treated as a Load.", so I guess I'm looking for a way to detect this state.

FYI. I've also tried looking into [InitializeOnLoadMethod] and [RuntimeInitializeOnLoadMethod] but to no avail.

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

4 Replies

· Add your reply
  • Sort: 
avatar image
1

Answer by lizhgong · Jan 22, 2019 at 02:47 PM

Maybe this comes too late. I just got the same problem and found an answer: You can use SessionState to store a key in it to avoid multiple invokes of the method.

 [InitializeOnLoad]
 public static class ProjectOpenEvent
 {
     private const string k_ProjectOpened = "ProjectOpened";

     static ProjectOpenEvent()
     {
         if (!SessionState.GetBool(k_ProjectOpened, false))
         {
             SessionState.SetBool(k_ProjectOpened, true);
             Debug.Log("[Debug]: project opened");
             
             // DO WHAT YOU WANT
         }
     }
 }
Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image ShawnFeatherly · Apr 04, 2019 at 03:23 AM 0
Share

Works great paired with EditorApplication.delayCall to ensure the Unity has finished loading. SessionState seems to be correctly cleared even if the UnityEditor previously crashed.

avatar image
0

Answer by Arsonistic · Jan 18, 2020 at 03:47 PM

EditorApplication.isPlayingOrWillChangePlaymode might be what you're looking for.

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
0

Answer by unity_gAMhN-EHnIqG0w · Sep 18, 2020 at 07:12 AM

 [InitializeOnLoad]
 public class Test
 {
     static Test()
     {
         const string k_ProjectOpened = "ProjectOpened";
         if (!SessionState.GetBool(k_ProjectOpened, false) && EditorApplication.isPlayingOrWillChangePlaymode == false)
         {
             SessionState.SetBool(k_ProjectOpened, true);
             //code here
         }
     }
 }

None of the answers helped me so I combined them and it worked...

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
0

Answer by ScottKane · Apr 01 at 08:11 PM

For anyone that comes across this, the above methods are completely wrong. It's running twice because the type is constructed both for play mode and edit mode. To properly handle this, you should be using the event that is being passed to you like so:

 using System;
 using UnityEditor;
 using UnityEngine;
 
 [InitializeOnLoad]
 public static class Program
 {
     static Program() => EditorApplication.playModeStateChanged += playMode => (playMode switch
     {
         PlayModeStateChange.EnteredPlayMode => () => Debug.Log("play enter"),
         PlayModeStateChange.ExitingPlayMode => () => Debug.Log("play exit"),
         _ => (Action)(() => { }) // ignore other states
     })();
     // the above cast on the default case lets us treat the return as an Action
     // so we wrap the switch expression in parenthesis and invoke using `()`
     // you could also call .Invoke() if you prefer
     // (this allows you to run the switch expression without an assignment)
 }

If you prefer you can use a normal switch:

 switch (playMode)
 {
     case PlayModeStateChange.EnteredPlayMode:
         Debug.Log("play enter");
         break;
     case PlayModeStateChange.ExitingPlayMode:
         Debug.Log("play exit");
         break;
     default: return;
 }

You could also set it to a method group:

 EditorApplication.playModeStateChanged += OnPlayModeChanged;

 static void OnPlayModeChanged(PlayModeStateChange playMode)
 {
     // switch here
 }






Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

8 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Initialising List array for use in a custom Editor 1 Answer

How to control class variables from an Editor Tool or external file? 2 Answers

Spline-based rotation 0 Answers

Editor plugin that runs all the time? 2 Answers

Editor script executing before variable updated 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges