Question by
abedawgg · Aug 28, 2020 at 09:29 PM ·
damagebulletsdestroygameobjectenemy healthhealth
Enemy damage script is not working
Hello, I've been trying to figure out this issue for many hours but I'm having no luck. I'm using projectile bullets and I basically want my enemy object to take an X amount of damage before the object is destroyed. I'm not really sure where the problem lies within the script. Any help would be greatly appreciated!
This is my Gun script
using UnityEngine;
using TMPro;
public class Gunbullets : MonoBehaviour
{
//bullet
public GameObject bullet;
public float damage = 10f;
// public GameObject impactEffect;
//bullet force
public float shootForce, upwardForce;
//Gun stats
public float timeBetweenShooting, spread, reloadTime, timeBetweenShots;
public int MagazineSize, bulletsPerTap;
public bool allowButtonHold;
int bulletsLeft, bulletshot;
//Recoil
public Rigidbody playerRb;
public float recoilForce;
//bools
bool shooting, readyToShoot, reloading;
//Reference
public Camera Camera;
public Transform attackPoint;
//Graphics
public GameObject muzzleFlash;
public TextMeshProUGUI ammunitionDisplay;
public bool allowInvoke = true;
private void Awake()
{
//make sure magazine is full
bulletsLeft = MagazineSize;
readyToShoot = true;
}
private void Update()
{
MyInput();
//Set Ammo Display
if (ammunitionDisplay != null)
ammunitionDisplay.SetText(bulletsLeft / bulletsPerTap + " / " + MagazineSize / bulletsPerTap);
}
private void MyInput()
{
//Check if allowed to hold down button and take correspinginput
if (allowButtonHold) shooting = Input.GetKey(KeyCode.Mouse0);
else shooting = Input.GetKey(KeyCode.Mouse0);
//Reloading
if (Input.GetKeyDown(KeyCode.R) && bulletsLeft < MagazineSize && !reloading) Reload();
//Reload automatically when trying to shoot without ammo
if (readyToShoot && shooting && !reloading && bulletsLeft <= 0) Reload();
//Shooting
if (readyToShoot && shooting &&!reloading && bulletsLeft > 0 )
{
//set bullets shot to 0
bulletshot = 0;
Shoot();
}
}
private void Shoot()
{
readyToShoot = false;
Ray ray = Camera.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0));
RaycastHit hit;
//check if ray hits something
Vector3 targetPoint;
if (Physics.Raycast(ray, out hit))
targetPoint = hit.point;
else
targetPoint = ray.GetPoint(75);
//calculate direction from attackPoint to targetPoint
Vector3 directionWithoutSpread = targetPoint - attackPoint.position;
//calculate spread
float x = Random.Range(-spread, spread);
float y = Random.Range(-spread, spread);
//calculate new direction with spread
Vector3 directionWithSpread = directionWithoutSpread + new Vector3(x, y, 0);
//instantiate bullet/projectile
GameObject currentBullet = Instantiate(bullet, attackPoint.position, Quaternion.identity);
//Roate bullet to shoot direction
currentBullet.transform.forward = directionWithSpread.normalized;
//Add force to bullet
currentBullet.GetComponent<Rigidbody>().AddForce(directionWithSpread.normalized * shootForce, ForceMode.Impulse);
currentBullet.GetComponent<Rigidbody>().AddForce(Camera.transform.up * upwardForce, ForceMode.Impulse);
//Instantiate muzzle flash, if you have one
if (muzzleFlash != null)
Instantiate(muzzleFlash, attackPoint.position, Quaternion.identity);
bulletsLeft--;
bulletshot++;
//invoke reset shot function (if not already invoked)
if (allowInvoke)
{
Invoke("ResetShot", timeBetweenShooting);
allowInvoke = false;
//Add recoil to player
playerRb.AddForce(-directionWithSpread.normalized * recoilForce, ForceMode.Impulse);
}
// if more than one bullets per Tap make sure to repeat shoot function
if (bulletshot < bulletsPerTap && bulletsLeft > 0)
Invoke("Shoot", timeBetweenShots);
Target target = hit.transform.GetComponent<Target>();
if (target != null)
{
target.TakeDamage(damage);
}
}
private void ResetShot()
{
readyToShoot = true;
allowInvoke = true;
}
private void Reload ()
{
reloading = true;
Invoke("ReloadFinished", reloadTime);
}
private void ReloadFinished()
{
bulletsLeft = MagazineSize;
reloading = false;
}
}
And this is my Enemy Script
using UnityEngine; using UnityEngine.AI;
public class AiTutorial : MonoBehaviour { public NavMeshAgent agent;
public Transform player;
public LayerMask whatIsGround, whatIsPlayer;
public float health;
public float damage;
//Patroling
public Vector3 walkPoint;
bool walkPointSet;
public float walkPointRange;
//Attacking
public float timeBetweenAttacks;
bool alreadyAttacked;
public GameObject projectile;
//States
public float sightRange, attackRange;
public bool playerInSightRange, playerInAttackRange;
public int life = 50;
public void OnCollisionEnter(Collision boom)
{
if (boom.transform.tag == "bullet")
{
health -= damage;
Destroy(boom.gameObject);
}
// the object that triggered this collision is tagged "bullet"
//if (boom.gameObject.tag == "bullet")
// {
// life += 1;
// if (life == 50)
// Destroy(gameObject);
// }
}
private void Awake()
{
player = GameObject.Find("Cylinderfps").transform;
agent = GetComponent<NavMeshAgent>();
}
private void Update()
{
//Check for sight and attack range
playerInSightRange = Physics.CheckSphere(transform.position, sightRange, whatIsPlayer);
playerInAttackRange = Physics.CheckSphere(transform.position, attackRange, whatIsPlayer);
if (!playerInSightRange && !playerInAttackRange) Patroling();
if (playerInSightRange && !playerInAttackRange) ChasePlayer();
if (playerInAttackRange && playerInSightRange) AttackPlayer();
}
private void Patroling()
{
if (!walkPointSet) SearchWalkPoint();
if (walkPointSet)
agent.SetDestination(walkPoint);
Vector3 distanceToWalkPoint = transform.position - walkPoint;
//Walkpoint reached
if (distanceToWalkPoint.magnitude < 1f)
walkPointSet = false;
}
private void SearchWalkPoint()
{
//Calculate random point in range
float randomZ = Random.Range(-walkPointRange, walkPointRange);
float randomX = Random.Range(-walkPointRange, walkPointRange);
walkPoint = new Vector3(transform.position.x + randomX, transform.position.y, transform.position.z + randomZ);
if (Physics.Raycast(walkPoint, -transform.up, 2f, whatIsGround))
walkPointSet = true;
}
private void ChasePlayer()
{
agent.SetDestination(player.position);
}
private void AttackPlayer()
{
//Make sure enemy doesn't move
agent.SetDestination(transform.position);
transform.LookAt(player);
if (!alreadyAttacked)
{
///Attack code here
Rigidbody rb = Instantiate(projectile, transform.position, Quaternion.identity).GetComponent<Rigidbody>();
rb.AddForce(transform.forward * 32f, ForceMode.Impulse);
rb.AddForce(transform.up * 8f, ForceMode.Impulse);
///End of attack code
alreadyAttacked = true;
Invoke(nameof(ResetAttack), timeBetweenAttacks);
}
}
private void ResetAttack()
{
alreadyAttacked = false;
}
public void TakeDamage(int damage)
{
health -= damage;
if (health <= 0) Invoke(nameof(DestroyEnemy), 0.5f);
}
private void DestroyEnemy()
{
Destroy(gameObject);
}
private void OnDrawGizmosSelected()
{
Gizmos.color = Color.red;
Gizmos.DrawWireSphere(transform.position, attackRange);
Gizmos.color = Color.yellow;
Gizmos.DrawWireSphere(transform.position, sightRange);
}
}
Comment
Your answer
![](https://koobas.hobune.stream/wayback/20220613010653im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How to make my gun do damge and destroy a object? 1 Answer
Apply Damage Universally 0 Answers
Enemy Can't Take Damage!!! 0 Answers
[Solved] I can't call Method from Referenced Script 1 Answer