Below is a simple framework for identifying what a player “shoots” at. A click on an object in unity will send a message to the log if an object is stuck by the “bullet”. If no object is struck, nothing will happen. From this framework we could very simply apply damage to the object struck, as well as any other desired effects upon shooting an object or player. The Serialized Field PlayerWeapon is where you could establish the damage, range, fire rate, and other unique attributes of each weapon object.
using UnityEngine;
public class PlayerShoot : MonoBehaviour {
[SerializeField]
private PlayerWeapon weapon;
[SerializeField]
private Camera cam;
[SerializeField]
private LayerMask mask;
void Start () {
if (cam == null)
{
Debug.LogError ("No camera referenced in PlayerShoot");
this.enabled = false;
}
}
void Update () {
if (Input.GetButtonDown ("Fire1"))
{
Shoot ();
}
}
void Shoot () {
RaycastHit _hit;
// If we hit something
if (Physics.Raycast (cam.transform.position, cam.transform.forward, out _hit, weapon.range, mask))
{
EnemyShot (_hit.collider.name);
}
}
void EnemyShot (string _colliderName) {
Debug.Log ("Enemy " + _colliderName + " has been Shot");
}
}