Hello,
I’m in Section 6: Laser Defender in the Complete C# Unity 2D course and the firing of lasers doesn’t work for me. I’m in Unity 6 and I noticed in the input system fire has now been replaced with attack, not sure if that has an affect on why it isn’t working for me.
My code for the Player:
using UnityEngine;
using UnityEngine.InputSystem;
public class Player : MonoBehaviour
{
[SerializeField] float moveSpeed = 5f;
Vector2 rawInput;
[SerializeField] float paddingLeft;
[SerializeField] float paddingRight;
[SerializeField] float paddingTop;
[SerializeField] float paddingBottom;
Vector2 minBounds;
Vector2 maxBounds;
Shooter shooter;
void Awake()
{
shooter = GetComponent<Shooter>();
}
void Start()
{
InitBounds();
}
void Update()
{
Move();
}
void InitBounds()
{
//boundaary for the player movement based off camera space
Camera mainCamera = Camera.main;
minBounds = mainCamera.ViewportToWorldPoint(new Vector2(0,0));
maxBounds = mainCamera.ViewportToWorldPoint(new Vector2(1,1));
}
void Move()
{
Vector2 delta = rawInput * moveSpeed * Time.deltaTime;
Vector2 newPos = new Vector2();
newPos.x = Mathf.Clamp(transform.position.x + delta.x, minBounds.x + paddingLeft, maxBounds.x - paddingRight);
newPos.y = Mathf.Clamp(transform.position.y + delta.y, minBounds.y + paddingBottom, maxBounds.y - paddingTop);
transform.position = newPos;
}
void OnMove(InputValue value)
{
rawInput = value.Get<Vector2>();
}
void OnFire(InputValue value)
{
if(shooter != null)
{
shooter.isFiring = value.isPressed;
}
}
}
My code for shooter:
using System.Collections;
using UnityEngine;
public class Shooter : MonoBehaviour
{
[SerializeField] GameObject projectilePrefab;
[SerializeField] float projectileSpeed = 10f;
[SerializeField] float projectileLifetime = 5f;
[SerializeField] float firingRate = 0.2f;
public bool isFiring;
Coroutine firingCoroutine;
void Start()
{
}
void Update()
{
Fire();
}
void Fire()
{
if (isFiring)
{
firingCoroutine = StartCoroutine(FireContinously());
}
else
{
StopCoroutine(firingCoroutine);
}
}
IEnumerator FireContinously()
{
while (true)
{
GameObject instance = Instantiate(projectilePrefab, transform.position, Quaternion.identity);
Destroy(instance, projectileLifetime);
yield return new WaitForSeconds(firingRate);
}
}
}
Thanks for the help!