- Home /
Console showing damage indicator, but damage multiplication is incorrect.
Hello,
I need my enemy to do 1 damage, trap to do 2 damage, and repair kit to heal 5 damage. My repair kit works fine and heals only when player is below max health and for the correct amount. I copied the same script for my trap and altered a bit to damage the player and when the trigger is activated, player goes from 10 health to 0 instantly.
Here is my trap script:
private void OnTriggerEnter(Collider other)
{
PlayerController controller = other.GetComponent<PlayerController>();
if (controller != null)
{
if (controller.currentHealth > 0)
{
controller.ChangeHealth(-2);
Destroy(gameObject);
Debug.Log("Player takes 2 damage from damage zone.");
}
}
}
And here is the relevant information from my player controller script:
public int maxHealth = 10;
public int currentHealth;
public float timeInvincible;
public float invincibleTimer;
public bool isInvincible = false;
void Start()
{
playerRb = GetComponent<Rigidbody>();
currentHealth = maxHealth;
}
void Update()
{
PlayerMovement();
LayTrap();
if (isInvincible)
{
invincibleTimer -= Time.deltaTime;
if (invincibleTimer < 0)
{
isInvincible = false;
}
}
}
private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.CompareTag("Enemy"))
{
collision.gameObject.GetComponent<EnemyController>().ChangeHealth(-1);
Debug.Log("Enemy takes 1 damage from player.");
}
}
public void ChangeHealth(int amount)
{
currentHealth = Mathf.Clamp(currentHealth = amount, 0, maxHealth);
if (amount < 0)
{
if (isInvincible)
{
return;
}
isInvincible = true;
invincibleTimer = timeInvincible;
}
if (currentHealth < 1)
{
Debug.Log("Game Over!");
}
if (currentHealth > 10)
{
currentHealth = 10;
}
}
Answer by evskii · Nov 10, 2021 at 07:37 PM
The clamp should say
currentHealth = Mathf.Clamp(currentHealth += amount, 0, maxHealth);
because what is happening is you are saying currentHealth = amount, and that is just setting the health to be equals to the damage you are taking rather than taking the damage away, then because your clamp is saying don't go below 0, it is just setting the health to be 0.
Thank you very much! Oversight when copying code, but I doubt I would've known if I'd seen it. I appreciate the explanation as well. Makes sense now and I've corrected the same issue for my enemies now :D
No worries! I make these mistakes many times a day.
Your answer
Follow this Question
Related Questions
Having problems with damage script 1 Answer
Problem with weapon and projectiles system in dealing damage to enemies? 1 Answer
Child object collision 2 Answers
Collision Damage, Hit points and Instantiate 1 Answer
Robot Not Taking Damage 0 Answers