- Home /
initial velocity for instantiated ragdoll prefab
Im instantiating a ragdoll prefab and I need it to have an initial velocity. I keep getting hit with null reference exceptions.
(the object is destroyed when the space bar is pressed)
public Rigidbody rag;
void OnDestroy()
{
rag = Instantiate(ragdoll, transform.position,transform.rotation) as Rigidbody;
rag.AddForce(100,100,100);//null reference at this line
}
Answer by syclamoth · Oct 25, 2011 at 01:33 AM
Are you instantiating an entire ragdoll prefab? If so, it's unlikely to have just a single rigidbody which controls the entire ragdoll. Try doing something like this, instead (without the public rigidbody, at the top)-
void OnDestroy()
{
Vector3 startingVelocity = rigidbody.velocity;
// Assuming you have a rigidbody on your character, otherwise work this out some other way
GameObject rag = Instantiate(ragdoll, transform.position, transform.rotation) as GameObject;
foreach(Rigidbody body in rag.GetComponentsInChildren<Rigidbody>())
{
body.velocity = startingVelocity;
}
}
Thanks alot. I was able to get the script working. I need to start using foreach more. Its helpful.
Otherwise just be sure that there's no kinematic rigidobdy in the ragdoll, and add a very big force in the source collider (the one to which all the others are necessarily connected, directly or indirectly)!
Your answer
![](https://koobas.hobune.stream/wayback/20220613020926im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Runtime prefab instantiation issue 1 Answer
NullReferenceException from a script after linking prefab with drag and drop in inspector. WTF? 1 Answer
Referencing gameObject from script after Instantiate 0 Answers
Object reference to set to instance on an instantiated object 1 Answer
NullReferenceException: Object reference not set to an instance of an object 1 Answer