Here is my script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Sprites;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class PlayerController : MonoBehaviour
{
public float speed;
public float jumpSpeed;
public Rigidbody2D rb;
public Text coinText;
public Text healthText;
public int maxHealth;
private Vector3 movement;
private bool canJump=false;
private int coinAmount=0;
private int healthPoints;
void Start ()
{
healthPoints = maxHealth;
rb = GetComponent<Rigidbody2D>();
bool canJump = true;
coinText.text = "Coins: " + coinAmount;
healthText.text = "Health: " + healthPoints + "/" + maxHealth;
}
void Update ()
{
transform.rotation = new Quaternion (0.0f, 0.0f, 0.0f, 0.0f);
if (Input.GetKey (KeyCode.A))
{
transform.Translate (-Vector3.right * Time.deltaTime * speed);
}
if (Input.GetKey (KeyCode.D))
{
transform.Translate (Vector3.right * Time.deltaTime * speed);
}
if (Input.GetKeyDown (KeyCode.Space)&&canJump)
{
rb.AddForce (transform.up * jumpSpeed);
canJump=false;
}
}
IEnumerator OnCollisionEnter2D(Collision2D col)
{
if (col.gameObject.tag == "Ground")
{
canJump=true;
}
if (col.gameObject.tag == "Enemy")
{
while (col.gameObject.tag == "Enemy")
{
healthPoints = healthPoints - 1;
healthText.text = "Health: " + healthPoints + "/" + maxHealth;
if (healthPoints <= 0)
{
SceneManager.LoadScene (sceneName: "Game Over");
yield break;
}
yield return new WaitForSeconds (1);
yield break;
}
}
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "Coin")
{
other.gameObject.SetActive (false);
coinAmount = coinAmount + 1;
coinText.text = "Health: " + coinAmount;
}
if (other.tag == "Void")
{
healthPoints = healthPoints - healthPoints;
healthText.text = "Extra Lives: " + healthPoints + "/" + maxHealth;
if (healthPoints <= 0)
{
SceneManager.LoadScene(sceneName:"Game Over");
}
}
}
}
I need to make it so that when I’m touching the enemy, my health points slowly go down, but the health points stop going down once I am no longer touching the enemy. How can I do this?