- Home /
Can anyone help with me with my attack script and enemy script?
When I attack I'm not sure why the enemy is not taking damage, my enemy script works i believe as when I set its health to 0 the enemy is deleted.
this is the script i believe has problems with it. Thanks
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AttackScript : MonoBehaviour {
public float hp = 10f;
public float toTarget;
public float range = 5f;
// Update is called once per frame
void Update () {
Attack ();
}
void Attack(){
RaycastHit hit;
Vector3 forward = transform.TransformDirection(Vector3.forward);
Vector3 origin = transform.position;
if(Physics.Raycast(origin, forward, out hit, range)){
if(hit.transform.gameObject.tag == "Enemy"){
hit.transform.gameObject.SendMessage("TakeDamage", hp);
}
}
}
}
Here is my enemy script.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyScript : MonoBehaviour {
public int enemyHealth = 50;
void TakeDamage(int hp){
enemyHealth -= hp;
}
// Update is called once per frame
void Update () {
if (enemyHealth <= 0) {
Destroy (gameObject);
}
}
}
@Scrim22 I tested your scripts, they are correct.
What I did:
Attached the EnemyScript to a gameobject, tagged Enemy
Attached the AttackScript to an FPSController/Camera
I suspect you might not have attached the AttackScript to the correct object. Or your intended mode of gameplay is not in first person shooter.
$$anonymous$$gestions, if you want to only attack on mouse click, or touch, please use this ins$$anonymous$$d:
void Update()
{
if (Input.Get$$anonymous$$ouseButtonDown(0))
Attack();
}
Cheers
Answer by EdwinChua · Apr 28, 2017 at 08:51 AM
@Scrim22 I tested your scripts, they are correct.
What I did:
Attached the EnemyScript to a gameobject, tagged Enemy
Attached the AttackScript to an FPSController/Camera
I suspect you might not have attached the AttackScript to the correct object. Or your intended mode of gameplay is not in first person shooter.
Suggestions, if you want to only attack on mouse click, or touch, please use this instead:
void Update()
{
if (Input.GetMouseButtonDown(0))
Attack();
}
Cheers