I have created a shooting game, here when I am shooting I have a c# script for damage for enemies.I have Used Raycast to Shoot enemies.if the RaycastHit becomes an enemy, it will be deducted it's health.It works properly.But the thing is, If I shoot objects except enemies it causes an error. I have provided some details about that.this is the script,
public class DamageSMG : MonoBehaviour
{
public int DamageAmount = 5;
public float TargetDistance;
public float AllowedRange = 50;
public RaycastHit Shot;
public int Firing;
void Update()
{
if(Input.GetButton("Fire1")){
if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward),out Shot))
{
TargetDistance = Shot.distance;
if (TargetDistance < AllowedRange)
{
if (Firing == 0)
{
Deduct();
}
}
}
}
}
public void Deduct()
{
Firing = 1;
Shot.transform.SendMessage("DeductPoints", DamageAmount);
StartCoroutine(Wait());
}
IEnumerator Wait()
{
yield return new WaitForSeconds(0.1f);
Firing = 0;
}
}
I am using an machine gun.therefore I have created Script to fire coutinously with 0.1sec break.When I press Fire1 button, The RayCastHit Object is received a message where the method called DeductPoints with the DamageAmount.As this Script my enemies are deduct point 5 by 5 every hit.Then Destroy the object.The Enemy script is this.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyScript : MonoBehaviour
{
public int EnemyHealth = 20;
void DeductPoints(int DamageAmount)
{
EnemyHealth -= DamageAmount;
}
// Update is called once per frame
void Update()
{
if (EnemyHealth <= 0)
{
Destroy(gameObject);
GlobalScore.GlobalScorecount += 1;
}
}
}
But my problem is when I shoot objects except Enemies(Ex: walls),The console gives an error.The error is like this SendMessage DeductPoints has no receiver How can I solve this error or is there any other way of Deducting enemy health with raycast? I can play the game with this error in UnityEngine.but it is not possible to Build the game.Please help me to Solve this..