Hello I am having trouble with the firing mechanic in the game. I have looked at a similar solution to my issue in this forum but it didn’t resolve the issue for me.
I have made sure to place the prefabs in the inspector and have rigidbodies on the projectile.
When I enter play mode I press the button to fire the laser in my case it is the space bar or LMB both of which don’t work. I have also placed a Debug.Log on the firing code which also doesn’t show in the console when used.
Here is the code I am using. If you have any suggestions as to why it’s not working please let me know.
Thank you.
PLAYER.CS
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class Player : MonoBehaviour
{
[SerializeField] float moveSpeed = 5f;
[SerializeField] float paddingLeft = 5f;
[SerializeField] float paddingRight = 5f;
[SerializeField] float paddingTop = 5f;
[SerializeField] float paddingBottom = 5f;
Vector2 minBounds;
Vector2 maxBounds;
Vector2 rawInput;
Shooter shooter;
void Awake()
{
shooter = GetComponent<Shooter>();
}
void Start()
{
InitBounds();
}
void Update()
{
Move();
}
void InitBounds()
{
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>();
}
public void OnShoot(InputValue value)
{
if(shooter != null)
{
Debug.Log("Projectile fired.");
shooter.isFiring = value.isPressed;
}
}
}
SHOOTER.CS
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Shooter : MonoBehaviour
{
[SerializeField] GameObject projectilePrefab;
[SerializeField] float projectileSpeed = 15f;
[SerializeField] float projectileLifeTime = 5f;
[SerializeField] float firingRate = 0.3f;
public bool isFiring;
Coroutine firingCoroutine;
void Start()
{
}
void Update()
{
Fire();
}
void Fire()
{
if (isFiring && firingCoroutine == null)
{
firingCoroutine = StartCoroutine(FireCountinuously());
}
else if(!isFiring && firingCoroutine != null)
{
StopCoroutine(firingCoroutine);
firingCoroutine = null;
}
}
IEnumerator FireCountinuously()
{
while (true)
{
GameObject instance = Instantiate(projectilePrefab, transform.position, Quaternion.identity);
Rigidbody2D rb = instance.GetComponent<Rigidbody2D>();
if(rb != null)
{
rb.velocity = transform.up * projectileSpeed;
}
Destroy(instance, projectileLifeTime);
yield return new WaitForSeconds(firingRate);
}
}
}