Hey guys, I am new to Unity and I am trying to debug this game for my class and I have been having issues. Besides most likely other issues my biggest concern right now is that two bullets are always spawned, no matter what happens. I will paste the script below. The script is placed on a capsule away from the camera and spawns the bullet that you see in the shooter when you get into game. I have an earlier version of the game already online that I will post so you can see the bug in action. Just click that link and make sure you aren’t using chrome, for whatever reason it doesn’t like chrome, unity thing.
Thanks for any help in advance! I don’t think this bug effects my grade since I already hit the other criteria I believe, this is just me trying to understand the error since the code appears to be some simple that I am not sure why it is being called twice (assuming it is being called twice).
using UnityEngine;
using System.Collections;
public class Gun : MonoBehaviour
{
public GameObject BulletPrefab;
public float FirePower;
public float ScreenToWorldDist = 10f;
public float NewBulletTime = 0.25f;
private Rigidbody _currentBullet;
private float _timer = 0f;
void Start ()
{
SpawnBullet();
}
void Update ()
{
Vector3 fireAt = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, ScreenToWorldDist));
if (Input.GetMouseButtonDown(0) && _currentBullet != null)
{
_currentBullet.useGravity = true;
Vector3 dir = (fireAt - transform.position).normalized;
_currentBullet.AddForce(dir * FirePower);
_timer = NewBulletTime;
}
if (_timer > 0f)
{
_timer -= Time.deltaTime;
if (_timer >= 0f )
{
SpawnBullet();
}
}
if (Input.GetKeyDown(KeyCode.Space))
Application.LoadLevel(0);
}
private void SpawnBullet()
{
GameObject bullet = Instantiate(BulletPrefab, transform.position, Quaternion.identity) as GameObject;
_currentBullet = bullet.GetComponent<Rigidbody>();
_currentBullet.useGravity = false;
}
}