- Home /
Question by
peterthepeter140 · Dec 28, 2017 at 02:32 PM ·
variablenullreferenceexceptionfloatboolshare
Null Reference Exception when using variable in another script
Both "Float currentMana" and "bool facingRight" is set to public in their respective scripts. All three scripts are on the same game object.
Error Message:
NullReferenceException: Object reference not set to an instance of an object FireBallSpell.fireProjectile () (at Assets/Scripts/Player/FireBallSpell.cs:46) FireBallSpell.FixedUpdate () (at Assets/Scripts/Player/FireBallSpell.cs:31)
Script where the errors occur:
public class FireBallSpell : MonoBehaviour
{
public Transform fireLocation;
public GameObject bullet;
float fireRate = 0.5f;
float nextFire = 0f;
playerHealth pH;
playerController pC;
SpellBook sB;
void start()
{
pH = gameObject.GetComponent<playerHealth>();
pC = gameObject.GetComponent<playerController>();
}
void FixedUpdate()
{
if (Input.GetAxisRaw("Jump") > 0)
{
fireProjectile();
pH.currentMana -= 10;
pH.manaSlider.value = pH.currentMana;
}
}
void fireProjectile()
{
if (Time.time > nextFire)
{
nextFire = Time.time + fireRate;
if (pC.facingRight)
{
Instantiate(bullet, fireLocation.position, Quaternion.Euler(new Vector3(0, 0, 0)));
}
else if (!pC.facingRight)
{
Instantiate(bullet, fireLocation.position, Quaternion.Euler(new Vector3(0, 0, 180f)));
}
}
}
}
2017-12-28.png
(8.5 kB)
Comment
Answer by GeorgeCH · Dec 28, 2017 at 02:42 PM
Start by doing a Debug.Log(pC) check to see whether the pC value isn't null (I suspect it might be).
void fireProjectile()
{
Debug.Log(pC);
// do other things
}
Answer by UDN_9a915d40-27e1-405b-b1cc-83be8be3e71d · Dec 28, 2017 at 04:05 PM
I suspect that you might have misspelt the class names on line 16-17. Shouldn't this:
pH = gameObject.GetComponent<playerHealth>();
pC = gameObject.GetComponent<playerController>();
instead be this:
pH = gameObject.GetComponent<PlayerHealth>();
pC = gameObject.GetComponent<PlayerController>();
Your answer
![](https://koobas.hobune.stream/wayback/20220612145358im_/https://answers.unity.com/themes/thub/images/avi.jpg)