Hey guys, I have a weird things happening…
I have no errors whatsoever yet I cannot hit or kill a simple enemy.
Raycast Shooting:
using UnityEngine;
using System.Collections;
public class RaycastShooting : MonoBehaviour {
public Transform effet;
public object bulletDamage = 100;
public float bulletDistance = 3000;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(new Vector3(Screen.width * 0.5f, Screen.height * 0.5f, 0f));
if (Input.GetMouseButtonDown(0)) {
if (Physics.Raycast(ray, out hit, bulletDistance)) {
hit.transform.SendMessage("ApplyDamage", bulletDamage, SendMessageOptions.DontRequireReceiver);
}
}
}
}
Enemy:
using UnityEngine;
using System.Collections;
public class Enemy : MonoBehaviour {
public int health = 100;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (health <= 0) {
Destroy(gameObject);
}
}
void ApplyDamage(int dmg) {
health -= dmg;
Debug.Log("You it mee");
}
}
Maybe my raycast shooting is messed up because it wont hit or kill my enemy?
The RaycastShooting script is attached to main camera while the enemy script is attached to a simple prefab.
For starters I would get rid of the Update and Start functions in your Enemy script. You only ever need to check if health is less then zero whenever you update health. And since the only way health is updated is through apply damage you only need to apply the check there.
I’m just making some guesses here, it’s late so I might not know what I’m talking about. But try reversing the bulletdirection. You might be firing the “bullet” across the wrong z-plane direction.
Try using hit.gameObject.SendMessage. I’m not quite sure, but I’m pretty sure sending it to the transform won’t work because the transform isn’t where the script it attached, the script is attached to the gameobject.
If that doesn’t work, it’s much easier to just get the script directly since you already have an instance of the object saved in the raycast hit.
If the ray hits, just do a simple check for the enemy, and call the applydamage function directly.
if (Input.GetMouseButtonDown(0)) {
if (Physics.Raycast(ray, out hit, bulletDistance)) {
if(hit.tag == "Enemy"){
Enemy enemyScript;
enemyScript = hit.gameObject.GetComponent<Enemy>();
enemyScript.ApplyDamage(bulletDamage);
}
}
}