Skip to content

Instantly share code, notes, and snippets.

@unity3dcollege
Created February 4, 2018 03:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save unity3dcollege/250b8625d097829150e04594fefeb046 to your computer and use it in GitHub Desktop.
Save unity3dcollege/250b8625d097829150e04594fefeb046 to your computer and use it in GitHub Desktop.
using UnityEngine;
public class Gun : MonoBehaviour
{
[SerializeField]
[Range(0.1f, 1.5f)]
private float fireRate = 0.3f;
[SerializeField]
[Range(1, 10)]
private int damage = 1;
[SerializeField]
private Transform firePoint;
[SerializeField]
private ParticleSystem muzzleParticle;
[SerializeField]
private AudioSource gunFireSource;
private float timer;
void Update()
{
timer += Time.deltaTime;
if (timer >= fireRate)
{
if (Input.GetButton("Fire1"))
{
timer = 0f;
FireGun();
}
}
}
private void FireGun()
{
//Debug.DrawRay(firePoint.position, firePoint.forward * 100, Color.red, 2f);
muzzleParticle.Play();
gunFireSource.Play();
Ray ray = new Ray(firePoint.position, firePoint.forward);
RaycastHit hitInfo;
if (Physics.Raycast(ray, out hitInfo, 100))
{
var health = hitInfo.collider.GetComponent<Health>();
if (health != null)
health.TakeDamage(damage);
}
}
}
using UnityEngine;
public class Health : MonoBehaviour
{
[SerializeField]
private int startingHealth = 5;
private int currentHealth;
private void OnEnable()
{
currentHealth = startingHealth;
}
public void TakeDamage(int damageAmount)
{
currentHealth -= damageAmount;
if (currentHealth <= 0)
Die();
}
private void Die()
{
gameObject.SetActive(false);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment