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;
}
}