Hello everyone, I’m trying to apply damage with if (Input.GetMouseButtonDown(0))
I’m trying to make a clicker game, where you attack monsters simply by clicking anywhere on the screen.
I can’t come up with the idea as to how to make such, I’m a newbie at programming, please freely share your ideas
Thank you in advance!
Trying to code something like such -
if(other.gameObject.tag == "Enemy")
{
if (Input.GetMouseButtonDown(0))
other.gameObject.GetComponent<EnemyHealth>().HurtEnemy(damagePerClick);
}
What does your enemy script look like? To begin with you need a variable to control the health and a function that runs if the health drops below 0. Something like:
public float health; //Set this var in the inspector
public void HurtEnemy(float dPC)
{
health -= dPC;
if(health <= 0)
Die();
}
void Die()
{
Destroy(gameObject); //Preferably replace this with death animation or such.
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class EnemyHealth : MonoBehaviour {
public int startingHealth; // The amount of health the player starts the game with.
public int currentHealth; // The current health the player has.
public Image healthBar; // Reference to the UI's health bar.
bool isDead; // Whether the player is dead.
bool damaged; // True when the player gets damaged.
void Awake()
{
// Set the initial health of the player.
currentHealth = startingHealth;
healthBar = healthBar.GetComponent<Image>();
}
// Update is called once per frame
void Update()
{
if (currentHealth <= (0))
{
Destroy(gameObject);
}
}
public void HurtEnemy(int amount)
{
// Reduce the current health by the damage amount.
currentHealth -= amount;
}
public void SetStartingHealth()
{
currentHealth = startingHealth;
}
}
this is the enemy script, I kinda fixed the click damage, but now I’m yet came close to another problem,
My idea is that I should get a script which would show one health bar and it never disappears, for example
Enemy is killed, bar just refills when new enemy spawns, also bar would show enemy’s hp in text, any idea of how I should implement such?
Really thankful !
click damage script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ClickDamage : MonoBehaviour
{
GameObject enemy; // Reference to the player GameObject.
EnemyHealth enemyHealth; // Reference to this enemy's health.
bool enemyInRange; // Whether player is within the trigger collider and can be attacked.
public int damagePerClick;
void Start()
{
// Setting up the references.
enemy = GameObject.FindGameObjectWithTag("Enemy");
enemyHealth = GetComponent<EnemyHealth>();
}
// Update is called once per frame
void Update()
{
if (gameObject.tag == "Enemy")
{
if (Input.GetMouseButtonDown(0))
gameObject.GetComponent<EnemyHealth>().HurtEnemy(damagePerClick);
}
}
}