Home > Net >  I am making a turret but it won't shoot
I am making a turret but it won't shoot

Time:11-15

I am making a turret that shoots a bullet at a set rate, but when the timer is done it doesn't spawn a new bullet even though it doesn't say i have any errors. the bullet has a simple script where it moves at a set speed either left or right, and gets destroyed on impact with an object. the turret does not have a collider right now so I know that's not the problem.

Here is the code for shooting:

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    
    public class TurretShoot : MonoBehaviour
    {
        public GameObject bullet;
        public int bullet_rate = 10;
        public int timer;
        public Transform SpawnPoint;

        void Start()
        {
            timer = bullet_rate * 10;
        }
    
        // Update is called once per frame
        void Update()
        {
            if (timer == 0)
            {
                Instantiate(bullet, SpawnPoint.transform);
                timer = bullet_rate * 10;
            }
            else
            {
                timer -= 1;
            }
        }
    }

Here is the bullet code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class BulletMove : MonoBehaviour
{
    public int moveDirection;
    public int moveSpeed;

    void Start()
    {
    }

    // Update is called once per frame
    void Update()
    {
        this.transform.position  = new Vector3(moveDirection * moveSpeed, 0, 0);
    }

    void onCollisionEnter2D(Collider2D col)
    {
        if (col.GetComponent<Collider>().name != "turret_top")
        {
            Destroy(this);
        }
    }
}

Here is the inspector for the turret:

enter image description here

CodePudding user response:

Probably what is happening is it get's destroyed when it spawns.

I don't have a collider on the turret

You aren't instantiating it at the turrent. You are simply setting the parent when you are instantiating it:

public static Object Instantiate(Object original, Transform parent);

Meaning it is probally spawning at Vector3.Zero and instantly gets de-spawn. Rather use the overload method of:

public static Object Instantiate(Object original, Vector3 position, Quaternion rotation);

That way you are spawning it the location you want. This is how you would go about it:

var bulletObj = Instantiate(bullet, SpawnPoint.transform.position, Quaternion.Identity);
bulletObj.transform.parent = SpawnPoint.transform;
timer = bullet_rate * 10;
  • Related