Null Reference Exception on Sprite Renderer
So I have two scripts interacting with each other. There is an AbilityController script attached to the player, and an AbilityFireball script that is attached to a prefab fireball. The AbilityController script instantiates the fireball prefab and sets its SpriteRenderer flipX to the flipX of the player's SpriteRenderer. However when run, every line of code is run appropriately (I checked with prints) and the only problem is that I get a NullReferenceException when trying to set the flipX of the instantiated fireball.
Here are the relevant parts of the two scripts
In AbilityController:
void Update () {
if (Input.GetKeyDown (KeyCode.Mouse0)) {
Transform a1 = Instantiate (ability1, transform.position, Quaternion.identity) as Transform;
//if (a1.GetComponent<AbilityFireball>().enabled)
a1.GetComponent<AbilityFireball> ().SetDirection (spriteRenderer.flipX);
}
}
And in AbilityFireball:
public override void Start () {
base.Start ();
spriteRenderer = GetComponent<SpriteRenderer> ();
Destroy (gameObject, duration);
}
public void SetDirection (bool direction) {
if (direction) {
print ("Flipping X");
spriteRenderer.flipX = true;
spriteRenderer.color = Color.red;
} else {
print ("Not Flipping X");
spriteRenderer.flipX = false;
spriteRenderer.color = Color.blue;
}
}
As I said before everything is called appropriately. When Mouse0 is pressed, it instantiates a fireball, and even sends the fireball the correct flipX value, however the fireball doesn't seem to recognize its own SpriteRenderer, and thus doesn't set the flipX. I don't understand what's wrong, especially considering I use the same exact syntax to set the SpriteRenderer of the player. The only notable difference is that the player is not instantiated. Does anyone have any idea what the problem could be?
Thanks.
Your answer
Follow this Question
Related Questions
List remains null after initialisation? 1 Answer
Null Reference in UnityStandardAssets.Utility.WaypointProgressTracker.Update 0 Answers
NullReferenceException when attempting to call a GameObject from within PointerEventData 1 Answer
GetComponent null, but it's attached to gameobject 1 Answer
(C#) Invoke giving null reference exception, crashing unity 0 Answers