Hey all!
RECAP: Why is this returning null and how can I fix it? To my knowledge its properly referenced.
LONG VERSION: I’ve been at this for a while now, and I can’t seem to find the root of my problem. In the game I’m creating, you intercept bombers by shooting their engines out. Pretty simple right? I have 2 scripts, one on the bomber itself named BomberBrain and one on it’s engines, BomberEngineHealth. What I want to happen is when an engine is shot, it adds +5 to the fallSpeed inside BomberBrain, so it slowly drifts downwards the more engines are shot. The problem is whenever I shoot out an engine, I immediately get “Failed to fall”… meaning the fallSpeed is never added to the BomberBrain’s fallSpeed variable.
public class BomberBrain : MonoBehaviour {
public float speed = 0.1f;
public float fallSpeed = 0.0f;
public GameObject explosion;
public Animation anim;
private BomberEngineHealth bomberEngineHealth;
void Start () {
bomberEngineHealth = GetComponent<BomberEngineHealth>();
}
void Update() {
//fly the bomber forwards
transform.Translate(Vector3.forward * Time.deltaTime * speed);
//bring 'er down
transform.Translate(Vector3.down * Time.deltaTime * fallSpeed);
}
void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "Ground")
{
Instantiate(explosion, gameObject.transform.position, gameObject.transform.rotation);
Destroy(gameObject, 0.1f);
Debug.Log("All hands lost!");
}
}
}
And here is the BomberEngineHealth script
public class BomberEngineHealth : MonoBehaviour {
public float engineHealth = 50f;
public GameObject explosion;
public bool hasExploded;
public GameObject smokeHolder;
private BomberBrain bomberBrain;
// Use this for initialization
void Start () {
smokeHolder.SetActive(false);
bomberBrain = GetComponent<BomberBrain>();
}
public void TakeDamage(float amount)
{
engineHealth -= amount;
if (engineHealth <= 0f)
{
Die();
Fall();
}
}
void Die()
{
if (!hasExploded)
{
Instantiate(explosion, gameObject.transform.position, gameObject.transform.rotation);
hasExploded = true;
smokeHolder.SetActive(true);
}
Destroy(gameObject, 0.1f);
}
void Fall()
{
if (bomberBrain != null)
{
Debug.Log("Fall");
bomberBrain.fallSpeed += 5;
}
else Debug.Log("Failed to fall");
}
}