Running a method multiple times

Hello,

I wrote a code, where when you hit “space” button, it launches a projectile. But when you spam space button, you get this:
Imgur

Basically, when you hit space, the actual bullet stops and new one is spawned. I understand, that once you run a method and you call it again, the current one stops where it was without going to the end, where the object is destroyed. It looks like this:

	public float bulletSpeed = 20f;

	public IEnumerator flyBullet(){
		Instantiate (gameObject);
		transform.position = new Vector3 (0, 0, playerScript.transform.position.z);	
		for (int i1 = 0; i1<=40; i1++){
		transform.position += transform.up * Time.deltaTime * bulletSpeed;
		yield return null;
		}
		Destroy (gameObject);
	}

	void Update () {
		if (Input.GetKeyDown ("space")) {
			StartCoroutine("flyBullet");
		}

	}

What I want is that you are able to fire several projectiles and all of the should reach desired distance and disappear.

I actually have no idea how to fix that since I’m a beginner with coding, so any help would be appreciated.

So I think you’re making things hard on yourself here by using a coroutine for the movement scripting.

In this case, since the bullet you’re instantiating is already a GameObject itself, why not let that object do the movement for you? Here’s what I would do instead:

First, let’s switch around the responsibility of your bullet script. I would do something like the following, where I use update to perform the movement…

public class BulletScript : MonoBehaviour {
	
	public float bulletSpeed = 20f;
	private Vector3 startPosition;
	private float maxDistance = 40f;
	
	// Use this for initialization
	void Start () 
	{
		// Save start position
		startPosition = transform.position;
	}
	
	// Update is called once per frame
	void Update () 
	{
		var newPosition = transform.position + transform.up * Time.deltaTime * bulletSpeed;
		if((newPosition - startPosition).magnitude > maxDistance) 
		{
			Destroy(gameObject);
		}
		else 
		{
			transform.position = newPosition;
		}
	}
}

Then in the player script, something like the following…

void Update () 
		{
			if (Input.GetKeyDown ("space")) 
			{
				// Instantiate -- or trigger a coroutine with a delay
				Instantiate (bulletObject, transform.position, Quaternion.identity);
			}
		}

This way, the scripts also make “simulated” sense. The player is “shooting” (spawning) the bullet.

It might not produce the result you want at first – I can’t tell what behavior you’re looking for exactly just from the image. But hopefully, you should be able to modify it easily enough.