- Home /
Running a script when Unity starts.
I'd like to run and editor script as soon as Unity launches. The closest I've been able to come is by using a CustomEditor on type Object, which launches as soon as something is selected.
Is it possible to run an editor script function when the Unity editor launches?
Answer by oxymoron · Feb 25, 2011 at 04:33 PM
edit: new link: http://answers.unity3d.com/questions/45186/can-i-auto-run-a-script-when-editor-launches-or-a.html
using UnityEngine;
using UnityEditor;
[InitializeOnLoad]
public class Autorun
{
static Autorun()
{
Debug.Log("Autorun!");
}
}
or if u want for the scene to be loaded, hook to the editor update callback
using UnityEngine;
using UnityEditor;
[InitializeOnLoad]
public class Autorun
{
static Autorun()
{
EditorApplication.update += RunOnce;
}
static void RunOnce()
{
Debug.Log("RunOnce!");
EditorApplication.update -= RunOnce;
}
}
Answer by qJake · Sep 09, 2010 at 07:55 PM
You could try a couple of different methods with OnEnable() (for example, on a class derived from "Editor", or on a custom editor window, or something like that). The only other way I could think of is to have a script with Start()
or Awake()
and have it set to ExecuteInEditMode
, though I'm not sure if that would work.
Thanks. I'll have to try the Editor window.
Currently, I'm using a class derived from Editor tied to UnityEngine.Object via the CustomEditor command. That runs the OnEnable method as soon as anything in the project or hierarchy is selected (which may be good enough), but not when Unity starts up.
Did you also try the constructor on the Editor-derived class? That might work, too :P
I did try the Editor-derived scripts. Their OnEnable methods aren't run until an object for which they're attached via the CustomEditor command is selected.
I also tried putting in an internal class whose constructor did what I want, and making a static instance of it. Again, the inner class's constructor wasn't run until an item was selected.
Answer by MattMaker · Oct 01, 2011 at 06:14 PM
I have taken the excellent code from the answer pointed to by vitamine and added it to the Community Wiki at http://www.unifycommunity.com/wiki/index.php?title=Autorun .
Cheers!
Your answer
Follow this Question
Related Questions
Updating object on inspector value changes in editor 1 Answer
How to check if a key is down in editor script 2 Answers
How to get notification of moving a GameObject in the hierachy when editing the scene? 1 Answer
Access Monobehavior Instance from Static Function of Editor Script 1 Answer
Are there any autosave scripts out there to protect against losing too much work? 4 Answers