Hi,
I’m a student of ’ Complete C# Unity Developer 2D: Learn to Code Making Games’ course. In the lecture 93 ‘Repeat Fire Coroutine’, my ‘FireContinously’ method doesn’t work correctly (The first challenge of this lecture). When I holding down the fire key it doesn’t repeat firing. Only fire when I click or push the fire button once. My Player.cs code is following…
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
// Configuration Parameters
[SerializeField] float moveSpeed = 10f;
[SerializeField] float padding = 1f;
[SerializeField] GameObject laserPrefab;
[SerializeField] float projectileSpeed = 10f;
[SerializeField] float projectileFiringPeriod = 0.1f;
float xMin;
float xMax;
float yMin;
float yMax;
// Start is called before the first frame update
void Start()
{
SetUpMoveBoudaries();
}
// Update is called once per frame
void Update()
{
Move();
Fire();
}
private void SetUpMoveBoudaries()
{
Camera gameCamera = Camera.main;
xMin = gameCamera.ViewportToWorldPoint(new Vector3(0, 0, 0)).x + padding; // Get Left Camera x boundaries
xMax = gameCamera.ViewportToWorldPoint(new Vector3(1, 0, 0)).x - padding; // Get Right Camera x boundaries
yMin = gameCamera.ViewportToWorldPoint(new Vector3(0, 0, 0)).y + padding; // Get bottom Camera x boundaries
yMax = gameCamera.ViewportToWorldPoint(new Vector3(0, 1, 0)).y - padding; // Get top Camera x boundaries
}
private void Move()
{
// Get Input for move in Horizontal (left or right) * Time.deltaTime (Framerate independent)
var deltaX = Input.GetAxis("Horizontal") * Time.deltaTime * moveSpeed;
var newXPos = Mathf.Clamp(transform.position.x + deltaX, xMin, xMax);
// Get Input for move in Vertical (up or down) * Time.deltaTime (Framerate independent)
var deltaY = Input.GetAxis("Vertical") * Time.deltaTime * moveSpeed;
var newYPos = Mathf.Clamp(transform.position.y + deltaY, yMin, yMax);
transform.position = new Vector2(newXPos, newYPos);
}
private void Fire()
{
if (Input.GetButtonDown("Fire1"))
{
StartCoroutine(FireContinously());
}
}
IEnumerator FireContinously()
{
Debug.Log("Fire!");
GameObject laser = Instantiate(laserPrefab, transform.position, Quaternion.identity) as GameObject; // Quaternion.identity) = no rotaion, Create laser as GameObject
laser.GetComponent<Rigidbody2D>().velocity = new Vector2(0, projectileSpeed);
yield return new WaitForSeconds(projectileFiringPeriod);
}
}
My Unity version is 2018.4.12f1
Please help me, Thank you.