'Unity Update() Function causing a NullReferenceException that isn't there if I manually call the function
I have a pretty "basic" combat class here. It has a Player and an Enemy. They are inherrited from a Character class and have values such as health, armor and ar (attack rating (damage)). I am trying to set the combat up in a way so that once you press a button (in this case, e), you attack the enemy and the enemy attacks you. I think this is most easily done by having a method in Update() which constantly checks whether or not my desired key is pushed, and if it is, to execute said method which has 2 attacks. I have rearranged the program so that the Player and Enemy are saved seperately in the methods "savePlayer" and "saveEnemy".
Relevant global objects:
public Player Player;
public EnemyCharacterCreator Enemy;
public Player savedPlayer;
public EnemyCharacterCreator savedEnemy;
public Text[] savedArray;
My constructor:
public Combat(Player Player, EnemyCharacterCreator Enemy, Text[] texxtArray)
{
savePlayer(Player);
saveEnemy(Enemy);
saveTextArray(texxtArray);
textChanges();
// FightLoop();
}
Aforementioned methods:
public void savePlayer(Player Player)
{
savedPlayer = Player;
}
public void saveEnemy(EnemyCharacterCreator Enemy)
{
savedEnemy = Enemy;
}
Combat-related code:
public void attackButton()
{
if (Input.GetKeyDown("e") == true)
{
FightLoop();
}
}
public void FightLoop()
{
PlayerAttack();
EnemyAttack();
textChanges();
}
public void PlayerAttack()
{
savedEnemy.health = savedEnemy.health - savedPlayer.ar;
}
public void EnemyAttack()
{
savedPlayer.health = savedPlayer.health - savedEnemy.ar;
}
Conceptually this should work fine, except it doesn't. When I "manually" execute FightLoop() in the constructor (commented out in the first code block) it works and the enemies health is reduced by 45 (which is my players' ar value), yet when I put attackButton() into the Update() function I get a NullReferenceException whenever I press e. 1 The error leads to line 74, which is the only line within the PlayerAttack() method:
savedEnemy.health = savedEnemy.health - savedPlayer.ar;
I put a breakpoint there and the savedEnemy object was null. I have no idea why, it is a global object and it works perfectly when I do it "manually", without Update(). Help would be appreciated.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
