Guest User

TankShooting

a guest
Nov 28th, 2018
90
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5.  
  6. public class TankShooting : MonoBehaviour
  7. {
  8. public Text ammoText;
  9.  
  10. public int ammo = 30; // Current ammo "in gun"
  11. public int totalAmmo = 100; // Total amount of ammo
  12. public int maxClipSize = 30; // Full reload amount
  13.  
  14. public GameObject shootObj; // Where shots spawn from
  15. public GameObject bulletPrefab; // Prefab we shoot
  16.  
  17. public AudioClip[] shootClip; // Shoot audio clips
  18. AudioSource audioSrc; // AudioSource for playing clips
  19.  
  20. void Start ()
  21. {
  22. // Gets audiosource from this obj
  23. audioSrc = GetComponent<AudioSource>();
  24. AdjustAmmo(0); // Updates ammoText
  25. }
  26.  
  27. void Update ()
  28. {
  29. // If you press space and have ammo > shoot
  30. if (Input.GetKeyDown(KeyCode.Space) && ammo > 0)
  31. {
  32. ammo--; // Ammo goes down by 1
  33. AdjustAmmo(0); // Updates ammoText
  34.  
  35. // Randomly change pitch and play random shoot clip (variety)
  36. audioSrc.pitch = Random.Range(0.75f, 1.25f);
  37. audioSrc.PlayOneShot( shootClip [ Random.Range(0,shootClip.Length) ] );
  38.  
  39. // Spawn bullet at shootObj position
  40. GameObject bullet = Instantiate(bulletPrefab, shootObj.transform.position, Quaternion.identity);
  41. // Add force to bullet
  42. bullet.GetComponent<Rigidbody>().AddForce(transform.forward * 1750);
  43. // Destroy bullet after 5 sec
  44. Destroy(bullet, 5);
  45. }
  46.  
  47. if(Input.GetKeyDown(KeyCode.R))
  48. {
  49. Reload();
  50. }
  51. }
  52.  
  53. // Fills up ammo as much as possible
  54. void Reload()
  55. {
  56. // Figure out how much ammo we need to reload
  57. int ammoToReload = maxClipSize - ammo;
  58.  
  59. // If we dont have enough total ammo for full reload
  60. if(totalAmmo < ammoToReload)
  61. {
  62. // Put all our ammo into current ammo
  63. ammo += totalAmmo;
  64. totalAmmo = 0;
  65. }
  66. else
  67. {
  68. // Full ammo
  69. ammo = maxClipSize;
  70. // Total ammo is subtracted by the amount we're reloading
  71. totalAmmo -= ammoToReload;
  72. }
  73. // Update text
  74. AdjustAmmo(0);
  75. }
  76.  
  77. public void AdjustAmmo(int adj)
  78. {
  79. // Adjust our total ammo
  80. totalAmmo += adj;
  81.  
  82. // Update ammo text
  83. ammoText.text = "AMMO: " + ammo + " / " + totalAmmo;
  84. }
  85. }
RAW Paste Data