0
\$\begingroup\$

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!

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

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);  
}
\$\endgroup\$
1
  • \$\begingroup\$ That answers this perfectly. Thank you for the clarification. I had not used custom method parameters, so this will make it much easier. \$\endgroup\$
    – Rj Joplin
    Commented Aug 7, 2015 at 19:20

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .