- Home /
Player wont take damage
Hey so for some reason my player wont take damage when he collides with an enemy can someone help me? the error I get is `NullReferenceException: Object reference not set to an instance of an object StoneGolemController.OnCollisionEnter (UnityEngine.Collision collision) (at Assets/Scripts/Enemies/StoneGolem/StoneGolemController.cs:51)
Here is my collide part
public void OnCollisionEnter(Collision collision)
{
if (collision.transform.tag == "Player")
{
attackDamage = Random.Range(minAttackDamage, maxAttackDamage);
critDamage = attackDamage * 3;
float randValue = Random.value;
if (randValue < critChance)
{
//Crit attack
Debug.Log("Crit attack " + critDamage);
PlayerController pHealth = collision.collider.GetComponent<PlayerController>();
pHealth.TakeDamagePlayer(critDamage);
}
else
{
//Normal attack
Debug.Log("Normal attack " + attackDamage);
PlayerController pHealth = collision.collider.GetComponent<PlayerController>();
pHealth.TakeDamagePlayer(attackDamage);
}
}
}
and here is the player takedamage part
public void TakeDamagePlayer(int damage)
{
currentHealth -= damage;
healthBar.SetHealth(currentHealth);
}
Answer by ahsen35813 · Apr 04, 2020 at 04:45 PM
This could help you a bit. https://answers.unity.com/questions/1712409/how-do-i-make-my-enemy-ai-attack.html?childToView=1712436#answer-1712436
If you use the same script and change it to OnCollisionEnter()
it should work, but that script has the advantage of being able to give the enemy an attack range and an attack cooldown as well. I hope you find this helpful!
P.S. That script will update the player's currentHealth
variable directly ins$$anonymous$$d of requiring an additional script in the player controller.
Answer by Makkkkus · Apr 04, 2020 at 08:55 PM
The TakeDamagePlayer() method should use a float, not an int.
Your answer
Follow this Question
Related Questions
Player Damage to enemy damage melee system 0 Answers
Dungeon Enemy Help 1 Answer
Player attacks once but the enemy takes double damages! 1 Answer
Question on Player Damage 1 Answer
auto select enemys 3 Answers