Object Reference not set to an instance of an object
Hey guys!
So I am working on a character controller script and I have run into an issue I can't figure out. I have my PlayerManager script set up with formulas to calculate hit points depending on whether you have a weapon equipped or not and if you do then it adds then weapons damage to your total hitpoints.
now where I am having issue is in this function here:
void equipWeapon()
{
if (Input.GetKeyDown(KeyCode.E))
{
GameObject.Find("Weapon").GetComponent<Weapon>().equipped = true;
GameObject.Find("PlayerWeapon").GetComponent<Weapon>().thisWeapon();
wepDam = GameObject.Find("PlayerWeapon").GetComponent<Weapon>().weaponDam;
}
else
{
GameObject.Find("Weapon").GetComponent<Weapon>().thisWeapon();
wepDam = GameObject.Find("Weapon").GetComponent<Weapon>().weaponDam;
}
}
This is called from the _PlayerManager().Update(); function, and it is meant to go like this: if Key E is pressed then set boolean equipped(In the weapon script) to true, then start the function Weapon().thisWeapon(); function is called which looks like this :
public void thisWeapon()
{
if (equipped == true)
{
weaponDam = Random.Range(4, 15);
this.name = "PlayerWeapon";
Debug.Log(this.name + " Equipped!");
}
else
{
weaponDam = 0;
}
}
All is fine until E is pressed, then I get the Error Object Reference not set to an instance of an object. But the script seems to still run if equipped == true ,the object name changes and the value of the hit points change as well...
any insight on what may be causing this error would be much appreciated as I have kinda hit a brick wall with it haha TIA
What is not set to an instance of an object? Error messages are there to help you - please include them in full when asking for help.
Sorry I wasn't sure what was causing the error, I have resolved, Just needed to put in an extra check in to stop the loop from Update();
Problem Solved!
I realised that since I was calling this function from update and then changing the object name withing the function that is where the error was co$$anonymous$$g from. so to remedy this I have made a bool named isEquipped and set it to false, so when the update calls the function it will only do anything if isEquipped is false if so then it takes appropriate action, if true then it will be more or less ignored.
Update looks like:
void equipWeapon()
{
if (isEquipped == false)
{
if (Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.E))
{
isEquipped = true;
GameObject.Find("Weapon").GetComponent<Weapon>().equipped = true;
GameObject.Find("Weapon").GetComponent<Weapon>().thisWeapon();
wepDam = GameObject.Find("PlayerWeapon").GetComponent<Weapon>().weaponDam;
isEquipped = true;
}
else
{
GameObject.Find("Weapon").GetComponent<Weapon>().thisWeapon();
wepDam = GameObject.Find("Weapon").GetComponent<Weapon>().weaponDam;
}
}
}