I’ve got no errors, so it’s just something I’m missing. The enemy gets destroyed if I set it to 0 so that works but when ever I hit it with the hammer it just doesn’t lose any hp. Explain it simply if you can. I’m trying my best to learn so every kind of feedback would be very useful I feel like it something to do with the currentHealth -= 2;
Thanks
using UnityEngine;
using System.Collections;
public class CombatScript : MonoBehaviour
{
public GameObject hammer;
public int currentHealth = 5;
public int enemyHealth = 6;
void update()
{
hammer = GameObject.FindGameObjectWithTag("Character_ThorModel_Hammer");
}
public void OnTriggerEnter(Collider other)
{
if(enemyHealth <= 0)
{
Destroy (gameObject);
}
}
void OnCollisionEnter (Collision col)
{
{
if(col.gameObject.name == "Character_ThorModel_hammer")
{
currentHealth -= 2;
print ("Hit");
}
}
}
void adjustHealth()
{
if(currentHealth < 0)
{
currentHealth = 0;
if(currentHealth > enemyHealth)
{
currentHealth = enemyHealth;
}
}
}
}
Its better to have the hammer to the damage. If the hammer colides with something on the “character” tag, for instance, you can do something like…
col.GetComponent<CombatScript>().DoDamage(2);
You’ll need a method that you can pass a damage variable through like…
public void DoDamage(int incomingDamage)
{ health -= incomingDamage; }
I would also recommend using a Property for your Health, so you can take care of it more effectively in the long run.
https://unity3d.com/learn/tutorials/modules/intermediate/scripting/properties
1 Like
anything involving collisions requires something in the collision to have a rigidbody (no rigidbody, no physics engine, no collision)
It’s a little odd to see Trigger and Collision code together, are you colliding with a trigger collider or a non trigger collider? (i.e. what type of collider is on the hammer?)
adjustHealth() never gets called… ? (also should really be AdjustHealth() functions are customarily capitalised)
I think one of the “key” things about writing code is making things small and have each bit handle it’s own “thing” and only that.
So having 1 script to handle “health”, it just keeps an eye on the number, has functions to be called when something else wants to change the health, checks for death etc. This script can then be put on anything that needs a health stat.
Then having 1 script to handle “being a weapon”, this handles just the damage, checks for hitting things, if that thing has a “health” script on it, tell the health script that damage was done using the functions on that health script. That way any object can have it added and it’s now a weapon.