Question by
dan1mk · Feb 11, 2020 at 07:01 PM ·
scripting problemunity 2dcrashingspace shootergun script
script causes unity to crash
So basically im trying to make a gun jam at random when it runs out of bullets, and you are supposed to enter the correct key, a randomized number 0-9 so that the gun unjams and reloads properly.. but when the gun jams my unity crashes.. What's wrong with the code? ps I am a pretty new coder so please dont judge if I have done something terribly wrong :D
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Weapon : MonoBehaviour
{
public Transform firePoint;
public GameObject bulletPrefab;
public int clipSize = 6;
private int ammo;
public float reloadTime = 1f;
private int JamChance;
public int chance = 30;
private KeyCode[] keys = { KeyCode.Alpha0, KeyCode.Alpha1, KeyCode.Alpha2, KeyCode.Alpha3, KeyCode.Alpha4,
KeyCode.Alpha5, KeyCode.Alpha6, KeyCode.Alpha7, KeyCode.Alpha8, KeyCode.Alpha9 };
private int current;
private int[] output = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
private string ammunition;
private bool isReloading = false;
public Text bText;
private void Start()
{
ammo = clipSize;
bText = GameObject.Find("BulletsText").GetComponent<Text>();
ammunition = ammo.ToString();
}
// Update is called once per frame
void Update()
{
if (isReloading)
return;
//Change so the ammo doesn't update every single frame
ammunition = ammo.ToString();
bText.text = ammunition;
//
//Reload if ammo is less or equal to zero
if (ammo <= 0)
{
JamChance = Random.Range(0, 100);
if (JamChance >= chance)
{
StartCoroutine(Reload());
return;
}
else
{
GunJam();
}
}
//Check if player hits the fire button, if yes then shoot
if (Input.GetButtonDown("Fire1"))
{
Shoot();
}
}
void Shoot()
{
//Shooting logic
Instantiate(bulletPrefab, firePoint.position, firePoint.rotation);
ammo--;
}
IEnumerator Reload()
{
//Display "Reloading..." in console
Debug.Log("Reloading...");
gameObject.GetComponent<Renderer>().material.color = new Color(1f, 0f, 0f);
isReloading = true;
yield return new WaitForSeconds(reloadTime);
isReloading = false;
ammo = clipSize;
gameObject.GetComponent<Renderer>().material.color = new Color(1f, 1f, 1f);
}
void GunJam()
{
gameObject.GetComponent<Renderer>().material.color = new Color(0f, 0f, 1f);
current = Random.Range(0, 9);
Debug.Log(output[current]);
if (Input.GetKeyDown(keys[current]))
{
StartCoroutine(Reload());
}
else
{
GunJam();
}
}
}
Comment