Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- using UnityEngine.UI;
- public class TankShooting : MonoBehaviour
- {
- public Text ammoText;
- public int ammo = 30; // Current ammo "in gun"
- public int totalAmmo = 100; // Total amount of ammo
- public int maxClipSize = 30; // Full reload amount
- public GameObject shootObj; // Where shots spawn from
- public GameObject bulletPrefab; // Prefab we shoot
- public AudioClip[] shootClip; // Shoot audio clips
- AudioSource audioSrc; // AudioSource for playing clips
- void Start ()
- {
- // Gets audiosource from this obj
- audioSrc = GetComponent<AudioSource>();
- AdjustAmmo(0); // Updates ammoText
- }
- void Update ()
- {
- // If you press space and have ammo > shoot
- if (Input.GetKeyDown(KeyCode.Space) && ammo > 0)
- {
- ammo--; // Ammo goes down by 1
- AdjustAmmo(0); // Updates ammoText
- // Randomly change pitch and play random shoot clip (variety)
- audioSrc.pitch = Random.Range(0.75f, 1.25f);
- audioSrc.PlayOneShot( shootClip [ Random.Range(0,shootClip.Length) ] );
- // Spawn bullet at shootObj position
- GameObject bullet = Instantiate(bulletPrefab, shootObj.transform.position, Quaternion.identity);
- // Add force to bullet
- bullet.GetComponent<Rigidbody>().AddForce(transform.forward * 1750);
- // Destroy bullet after 5 sec
- Destroy(bullet, 5);
- }
- if(Input.GetKeyDown(KeyCode.R))
- {
- Reload();
- }
- }
- // Fills up ammo as much as possible
- void Reload()
- {
- // Figure out how much ammo we need to reload
- int ammoToReload = maxClipSize - ammo;
- // If we dont have enough total ammo for full reload
- if(totalAmmo < ammoToReload)
- {
- // Put all our ammo into current ammo
- ammo += totalAmmo;
- totalAmmo = 0;
- }
- else
- {
- // Full ammo
- ammo = maxClipSize;
- // Total ammo is subtracted by the amount we're reloading
- totalAmmo -= ammoToReload;
- }
- // Update text
- AdjustAmmo(0);
- }
- public void AdjustAmmo(int adj)
- {
- // Adjust our total ammo
- totalAmmo += adj;
- // Update ammo text
- ammoText.text = "AMMO: " + ammo + " / " + totalAmmo;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement