Hi so I have a shooting script and a bullet prefab inside of that.
The code for the script is here:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Shooting : MonoBehaviour
{
[Header("Gun Stats")]
public int damage;
public float timeBetweenShooting, range, reloadTime, timeBetweenShots, bulletForce;
public int magazineSize, bulletPerShot;
public bool allowButtonHold;
int bulletsLeft, bulletsShot;
//Bools
[HideInInspector]public bool shooting, canShoot, reloading;
[Header("References")]
public GameObject bullet;
private Transform firePoint;
private void Awake()
{
bulletsLeft = magazineSize;
canShoot = true;
}
private void Start()
{
firePoint = transform.Find("FirePoint");
}
private void Update()
{
MyInput();
}
private void MyInput()
{
if (allowButtonHold) shooting = Input.GetButton("Fire1");
else shooting = Input.GetButtonDown("Fire1");
if (Input.GetKeyDown(KeyCode.R) && bulletsLeft < magazineSize && !reloading) Reload();
//Shoot
if (canShoot && shooting && !reloading && bulletsLeft > 0)
{
bulletsShot = bulletPerShot;
Shoot();
}
}
private void Reload()
{
reloading = true;
Invoke("ReloadFinished", reloadTime);
}
private void ReloadFinished()
{
bulletsLeft = magazineSize;
reloading = false;
}
void Shoot()
{
canShoot = false;
GameObject bullet = Instantiate(bullet, firePoint.position, firePoint.rotation);
Rigidbody2D rb = bullet.GetComponent<Rigidbody2D>();
rb.AddForce(firePoint.transform.right * bulletForce, ForceMode2D.Impulse);
bulletsLeft--;
bulletsShot--;
Invoke("ResetShot", timeBetweenShooting);
if (bulletsShot > 0 && bulletsLeft > 0)
Invoke("Shoot", timeBetweenShots);
}
private void ResetShot()
{
canShoot = true;
}
}
At this line: GameObject bullet = Instantiate(bullet, firePoint.position, firePoint.rotation);, I am getting an error saying "Use of unassigned local variable “bullet”.
I have assigned the prefab in the inspector so I don’t know what is going on. Any help?