IMPORTANT: Unity Prefabs cannot store references to Scene Objects!
When you create a prefab from a scene GameObject, all references to objects in the scene will be lost when you save the project!
NOTE: This is a Unity, not PlayMaker specific, restriction.
This tutorial shows how you can reference scene objects in Prefabs.
We'll work through a simple example, step by step:
In this scene a Director FSM sets the FOV of the Main Camera. The Director is a scene object so it can store a reference to the Main Camera.
Now let's say you make the Director a prefab so that it can be re-used in multiple scenes:
Note, the GameObject parameter is lost in the prefab, since it is a scene object. If you add this prefab to a scene it doesn't work:
There are 2 main strategies to fix this:
- Use an exposed variable that can be set on the instance in the scene.
- Use an action to find the scene object at runtime.
Both strategies start with using a variable for the GameObject parameter in the prefab:
Now we just need to make sure this variable is set properly.
We'll take a look at 2 ways to do this:
1. Use an Exposed Input Variable
Select the MainCamera variable in the Variables Manager and check Inspector (or Input in 1.9.1+):
Select the Director Instance in the Scene and select the FSM tab:
Set the MainCamera variable to the scene's Main Camera:
The Director will now run properly in the scene:
2. Use Actions to Find Scene Objects
Alternatively you can use an action to find the Main Camera:
Some other ways to find scene objects:
- Find Game Object by name or tag.
- Find Child by name, including path.
- Get Child by name or tag.
- Get Child Num to get a child by index.
Many other actions return GameObjects in different ways (after a collision, in event data...). So there is usually a way to set up the prefab so it can find the scene object it needs to work with at runtime.
Use either exposed variables or actions to setup references to scene objects in prefabs.
NOTE: The same strategies apply to FSM Templates since they are project assets like prefabs.