I have a projectile and an enemy, but I want the enemy to decrease the heath variable when it touches the projectile.
I tried to shoot projectiles but it did not decrease the health.
`using System.Collections; using System.Collections.Generic; using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Health : MonoBehaviour
{
public int startHealth = 20;
public int health;
// Start is called before the first frame update
void Start()
{
health = startHealth;
}
// Update is called once per frame
void OnTriggerEnter2D(Collider2D col)
{
Debug.Log("Hit");
if (col.gameObject.tag == "PlayerProjectile")
{
health = health - 1;
}
}
void LateUpdate()
{
if (health < 1)
{
Destroy(gameObject);
}
}
}
You're probably missing one or more things:
A Rigid body inside both your bullet and your enemy.
A collider (non-trigger) inside both game objects.
The layer collision matrix must match between both objects (you can learn more of this inside this document: https://docs.unity3d.com/Manual/LayerBasedCollision.html)
If the bullet is too fast, you must change the "Collision Detection Mode", also, you can learn more here: https://docs.unity3d.com/ScriptReference/Rigidbody-collisionDetectionMode.html
I hope I help you!