My projectiles aren't going anywhere

I followed the code as instructed but I can’t figure out why it isn’t functioning correctly. My projectiles are creating, and not spamming like crazy. But they dont have any velocity for some reason. Any help would be greatly appreciated.

Here is my code for my Shooter.cs

using System.Collections;
using System.Collections.Generic;
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 == null)
    {
        firingCoroutine = StartCoroutine(FireContinuously());

    }
    else if(!isFiring && firingCoroutine != null)
    {
        StopCoroutine(firingCoroutine);
        firingCoroutine = null;
    }
}
IEnumerator FireContinuously()
{
    while (true)
    {
        GameObject instance = Instantiate(projectilePrefab, transform.position, Quaternion.identity);

        Rigidbody2D instanceRigidbody = instance.GetComponent<Rigidbody2D>();
        if(instanceRigidbody != null)
        {
            instanceRigidbody.velocity = transform.up * projectileSpeed;
        }

        Destroy(instance, projectileLifetime);

        yield return new WaitForSeconds(firingRate);
    }
}

}

2 Likes

Figured out my issues. I had accidentally put the component on the child game object of the projectile where the sprite was and not the parent game object "Projectile_Player ". Everything works now.

I suppose it would have worked if I grabbed a child component somehow or just used the child game object as my prefab in the serialized fields. Maybe I’ll try that one day.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms