- Home /
Awake() not called on script referenced directly from Project window
I have a GameObject called TestObject in the HIERARCHY. It has a SimpleScript component.
public class SimpleScript : MonoBehaviour
{
public GameScreen activeScreen;
void Start()
{
activeScreen.Test();
}
}
The GameScreen component looks like this:
public class GameScreen : MonoBehaviour
{
void Awake()
{
print("Awake called.");
}
public void Test()
{
print("Test Successful.");
}
}
In my PROJECT view, I have a prefab called SplashScreen which has a GameScreen added to it as a component. There's nothing else on it.
I drag the SplashScreen prefab onto the inspector for the TestObject's activeScreen field. When I run the game, the words "Test Successful" are printed to the output window, but the words "Awake called" are not.
It seems like a prefab dragged from the PROJECT view doesn't have Awake() called on it. But if I drag it to the HIERARCHY view first to create an instance of it, and then drag that instance onto the TestObject's activeScreen field, it works fine.
Is there some way to make Awake() call on the prefab dragged from the PROJECT view?
Answer by whydoidoit · Apr 17, 2013 at 12:32 PM
The system is behaving as designed.
When you dragged it from the project window onto a variable in the inspector you don't have an instance of it - you have the prefab reference (which obviously shouldn't wake up). You are expected to make an instance of that item to use it.
When you create an instance out of the prefab, the instance will have Awake() called on it.
Okay I understand that, but why does the method work if there's no instance?
Because you are accessing the reference instance in the project. This is useful so that you can modify the object before instantiating a copy. ($$anonymous$$g. setting properties that would be used by Awake).
You shouldn't access these objects for any other reason however.
Technically there is an instance in memory which is created when the game loads, but it's not part of the scene and game mechanics. It's just a "source object" for Instantiate which will create a clone in your actual scene. The pure C# / managed part of the object works, but the actual engine binding isn't there. Awake is a callback that is called from the engine itself. Only objects in the scene which are active and enabled are updated.
From Unity's point of view this object isn't really there.