How to instantiate a prefab with initial velocity?

I have found this Instantiate with initial velocity - Unity Answers but there’s no such thing as Object.AddForce() in C#.

What happens now is that I am firing my weapon and instantiates in front of my car, which I will then run over because it starts with 0 velocity. I would like to have the weapon start with the same velocity as my car.

            // forward firing start location
			Vector3 start = transform.position;
			start.z += localVelocity.normalized.z*5;

			if (weapons[0] == Arsenal.Spin)
			{
				Object obj = Instantiate(Prefab[0], start, transform.rotation);	
			}

2 Answers

2

thef1chesser’s answer works perfectly for older version of Unity.

For people who are using Unity 5, replace

obj.rigidbody.velocity

with

obj.GetComponent<Rigidbody2D>().velocity

That should do the trick for Unity 5 users :wink:

It should be: obj.GetComponent<Rigidbody>().velocity Rigidbody2D is only for 2D and was previously accessed with rigidbody2D

// forward firing start location
Vector3 start = transform.position;
start += transform.forward.normalized * 10;

			if (weapons[0] == Arsenal.Spin)
			{
				GameObject obj = (GameObject)Instantiate(Prefab[0], start, transform.rotation);
				obj.rigidbody.velocity = transform.rigidbody.velocity;
			}

this gives me the result I was searching for.