I don’t understand why we are not getting a Null reference exception after moving the transform.LookAt() to the Start() method. As I understand, the Start() method gets executed when the script is enabled. So now we are calling GetPosition() in the Start() method, and GetPosition contains a call to target.GetComponent(), which just after the instantiation should be null, since we will assign it in Weapon.cs after the call instantiate de Projectile (see code below).
The only reason I see for us not getting the exception is that the Start() method on Projectile is called after
projectileInstance.Target = target;
in Weapon.cs.
Which messes my understanding of the execution order. Is that what is happening?
public class Projectile : MonoBehaviour {
private Health target;
private float damage;
// ...
public Health Target { get => target; set => target = value; }
public float Damage { get => damage; set => damage = value; }
private void Start() {
transform.LookAt(GetPosition()); // This is now executed after instantion
}
void Update() {
if (target != null) {
//transform.LookAt(GetPosition());
transform.Translate(Vector3.forward * speed * Time.deltaTime);
}
}
private Vector3 GetPosition() {
CapsuleCollider targetCollider = target.GetComponent<CapsuleCollider>();
// This line above I believe should raise the exception
if (targetCollider != null) {
return target.transform.TransformPoint(targetCollider.center);
} else {
return target.transform.position;
}
}
//...
}
Back in Weapon.cs, we call the instantiation here:
public void LaunchProjectile(Transform rightHand, Transform leftHand, Health target) {
Projectile projectileInstance = Instantiate(projectile, GetHandTransform(rightHand, leftHand).position, Quaternion.identity);
projectileInstance.Target = target;
projectileInstance.Damage = weaponDamage;
}
PS. Ok, I made some “log debug” and verified that the Start() method in Projectile is called not just after instantiation, but instead after LaunchProjectile is finished… I guess my question is now, why exactly is the Start() method called?