Shooting bullets from a ship

I’m new to unity and I’m trying to figure out what the best practices are to shoot bullets from a ship that I currently have moving around in my scene. Basically, I am using the Dual Joysticks prefab from the Standard Assets (Mobile) package and when the left joystick is touched, it moves the ship. All is well there, but I need to make the ship start shooting bullets in the direction the ship is facing while the right joystick is pressed. I have been looking into prefabs and object pools but I think I need a basic example of how to generate a bullet prefab at my ships’ location, and then move the bullets and check each ones collision with other objects.

Here is what I am thinking:

// Check if the joystick is touched
if (rightJoystick.IsFingerDown())
{
    // Generate a new bullet (will eventually pull from an object pool of pre-generated bullets)

    // Add bullet to active bullets array
}

updateBulletPositions(); // Move each bullet in the active bullets array
checkCollisions(); // This is where bullets would be removed if there was a collision or lifetime is passed

If someone wouldn’t mind providing me with a simple example, or a good resource to look at on how to generate bullet prefabs at runtime, while keeping everything as optimized as I can that would be great.

Let me know if you need more information from me! Thanks!

I would say you should check out “Instantiate” in the Script Reference.

Maybe OnCollisionEnter,OnCollisionStay,OnCollisionExit is intresting for you aswell

Here is one approach. Place an empty game object in front of the barrel of the gun and make it a child of the barrel. The forward (positive Z) vector of the empty must point in the same direction as the barrel. This is the spawn point. Since it is a child of the barrel, it will move and rotate with the barrel. Here is a starter script to attach to the empty game object. It’s not very sophisticated, but it does reuse the bullets. Drag the prefab for your bullets onto goProfilePrefab in the inspector.

public class Shooter : MonoBehaviour {
	
	public GameObject goProjectilePrefab;
	private GameObject[] argoProjectiles = new GameObject[20];
	private int iNext = 0;
	private float fMag = 500.0f;

	void Start () {
		for (int i = 0; i < argoProjectiles.Length; i++) {
			argoProjectiles *= (GameObject)Instantiate (goProjectilePrefab);*

_ argoProjectiles*.SetActive (false);_
_
}_
_
}*_

* void Update () {*
* if (Input.GetKeyDown(KeyCode.Space)) {*
* GameObject go = argoProjectiles[iNext++];*
* if (iNext >= argoProjectiles.Length) iNext = 0;*
* go.SetActive (true);*
* go.rigidbody.velocity = Vector3.zero;*
* go.transform.position = transform.position;*
* go.transform.rotation = transform.rotation;*
_ go.rigidbody.AddForce (transform.forward * fMag);_
* }*
* }*
}