Unity 5.3.4f1, following the SpaceShooter tutorial:
Two scripts are attached to a ship:
- Mover, which moves the ship downwards
- Evader, which moves the ship from side to side
Mover code:
void Start ()
{
GetComponent<Rigidbody>().velocity = transform.forward * speed;
}
Evader code:
void Start ()
{
currentSpeed = GetComponent<Rigidbody>().velocity.z;
}
void FixedUpdate ()
{
GetComponent<Rigidbody>().velocity = new Vector3 (newManeuver, 0.0f, currentSpeed);
}
Key things to note:
- Mover sets the velocity to (0, 0, -speed) in Start()
- Evader grabs velocityZ in Start()
- Evader changes velocityX, keeping velocityZ the same
In the video tutorial,
- Ship objects are instantiated, and
- Script order is Mover > Evader
and everything works. Ships move downwards, and from side to side.
However, if either:
- Ship objects are placed in the scene, or
- Script order is Evader > Mover
The ship only moves from side to side.
This suggests the following to me:
- Start() order of scripts of objects placed in the scene is simultaneous; this matches the documentation at Unity - Manual: Order of execution for event functions
For objects added to the scene, the
Start function will be called on all
scripts before Update, etc are called
for any of them. Naturally, this
cannot be enforced when an object is
instantiated during gameplay.
- Start() order of scripts of instantiated objects is defined by the script order in inspector
I haven’t seen anything in documentation to confirm the second point, though the video tutorial seems to rely on this. Does it work this way, can I rely on this behaviour? If not, how would I change up the above code to make it work reliably? Unity - Manual: Script Execution Order settings seems to only modify the script execution order of Awake, OnEnable and Update only.