x


'Awake' not called first after scripts are recompiled during execution

I have an 'awake' function which sets up an instance, like so:

public static instance MySingleton
{
get;
private set;
}

void Awake()
    {
        Instance = this;
    }

This works fine, no problems.

However if I change a script during run time and unity does its recompilation 'Awake' isn't called on 'MySingleton' and another script from its normal update routine attempts to access it causing a null reference exception...

Any idea how I could make sure 'awake' is called straight after a script is recompiled or does Unity not provide a way to handle this?

more ▼

asked May 16 '12 at 11:57 AM

chillypacman gravatar image

chillypacman
206 49 64 74

you can stop the execution and run it again. what is the problem in it?

May 16 '12 at 12:00 PM flamy

the problem is I'd like to be able to take advantage of Unity's ability to dynamically compile scripts at run time.

May 16 '12 at 12:04 PM chillypacman

Dynamic compilation is broken. In my experience it always raise some exception.

May 16 '12 at 02:53 PM Kryptos
(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

Dynamic compilation isn't really a good idea, but that code is dangerous anyway. You should call an Init function both in get and Awake if the instance is null, that way it's initialize not matter which one is called first.

I added a simple way to have singleton with monobehaviour to the wiki if you're interested.

more ▼

answered May 16 '12 at 03:21 PM

Berenger gravatar image

Berenger
11k 12 19 53

ah yes that code works perfectly, thank you so much for taking the time to put it in the wiki!

May 17 '12 at 10:05 AM chillypacman
(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

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

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x202
x59
x55

asked: May 16 '12 at 11:57 AM

Seen: 544 times

Last Updated: May 17 '12 at 10:05 AM