Created
February 4, 2018 03:06
-
-
Save unity3dcollege/250b8625d097829150e04594fefeb046 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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