# Instantiation of multiple objects with varying velocities

I am looking to multiple objects of the same prefab at the same time with varying velocities.

public GameObject prefab;
public float xDirection;
public float yDirection;
void Update () {
GameObject prefab1 = Instantiate
(prefab,transform.position,quaternarion.identity) as GameObject;
GetComponent<RigidBody2D>().velocity = new Vector2 (xDirection,yDirection);
}


I want to create three instances at once, but have the x/y direction be different. I am looking at creating an instance at three separate velocities. I know I can do something like this using

void Update () {
if (Input.GetKey(KeyCode.space)){
xDirection = 1f;
yDirection = 1f;
shootObject();
xDirection = 2f;
yDirection = 2f;
shootObject();
xDirection = 2f;
yDirection = 2f;
shootObject();
}
}
void shootObject () {
GameObject prefab1 = Instantiate
(prefab,transform.position,quaternarion.identity) as GameObject;
GetComponent<RigidBody2D>().velocity = new Vector2 (xDirection,yDirection);
}


but I feel like there is something else that I should be able to do to simplify this even further since this seems to be very messy code.

(I apologize if something seems a little odd. Have only been coding for around a few weeks.)

Thank you for the help!

There's not too much wrong with your code except you don't seem to be aware of how to use method parameters. I don't expect I need to explain much more than to show you the code...

void Update () {
if (Input.GetKey(KeyCode.space)){
shootObject(1.0f, 1.0f);
shootObject(2.0f, 2.0f);
shootObject(2.0f, 2.0f);
}
}
void shootObject(float xDirection, float yDirection) {
GameObject prefab1 = Instantiate(prefab,transform.position,quaternion.identity) as GameObject;
GetComponent<RigidBody2D>().velocity = new Vector2(xDirection, yDirection);
}

• That answers this perfectly. Thank you for the clarification. I had not used custom method parameters, so this will make it much easier. – Rj Joplin Aug 7 '15 at 19:20