Instantiate new gameobjects on collision, keeping velocity, up to a cap

I’m essentially trying to duplicate Hanzo’s scatter arrow from Overwatch, but I’m not having any luck.
I have a ScatterArrow Game object and attached a ScatterArrow script that will handle the logic.

I can create more ScatterArrows on collision, but I don’t know how to keep the velocity and stop the arrows from spawning after a certain amount of collisions.

For limiting the spawns I’ve considered an iteration variable, which I increase each collision until it reaches a cap and no more arrows are made.

Here is my code:

public class ScatterArrow : MonoBehaviour {

	public int iteration;

	// Use this for initialization
	void Start () {
		
	}
	
	// Update is called once per frame
	void Update () {
		
	}

	void OnCollisionEnter2D (Collision2D coll)
	{
		//if the arrows have rebounded less than three times add new scatter arrows
		if (iteration != 3){
			
			GameObject scatterArrow = Instantiate (Resources.Load ("ScatterArrow")) as GameObject; 

			//match position of the current arrow
			scatterArrow.transform.position = this.gameObject.transform.position;

			//add velocity to the new arrow

		}

		Destroy (this.gameObject);
	}
}
  • How would I keep the velocity of the new arrow the same as the old arrow? I have a RigidBody2D attached to the GameObject but I can’t access it in code (it’s crossed out in the intellisense preview).
  • Is there a way I can make the spawns stop after a few iterations without making another class? Right now increasing the new arrows iteration to +1 takes it from the prefab default of 0, and makes it 1, so it never reaches 3 and continuously respawns in the same position.

Any help would be appreciated, thanks!

As for accessing the rigidbody it is crossed out in intellisense since the variable is deprecated but you can manually cache a reference to rigidbody in the Start(), Something like this.

Rigidbody2D rb;
void Start(){ rb = GetComponent<Rigidbody2d>(); }

For keeping the same velocity as this component, you can then use this rb.velocity while Instantiating your new scatter arrow

Lastly for creating exactly 3 arrows this iteration thing seems a bit weird.
The simplest way to get 3 arrows is to just Instantiate 3 arrows like this

Or I’m guessing you would need the number of arrows generated configurable then you should have a parameter

public GameObject arrowPrefab; 
int numOfArrowsToCreate;

void OnCollisionEnter2D(){
    //Other stuff

    for(i=0; i<numOfArrowsToCreate; i++)
    {
        GameObject s = Instantiate (arrowPrefab, transform.position, transform.rotation); 
       //You can set each arrows velocity here as well using rb.velocity
     }
}

To extend this thought you can imagine that the numOfArrowsToCreate might generate random numbers every time they are called. That way you will have random number of scattered arrows just like OverWatch