- Home /
Question by
ColdComfort · Apr 24, 2019 at 03:42 AM ·
c#physicsrigidbodyinstantiate
Set Rigidbody.velocity for an instantiated object
Hello!
I'm trying to instantiate an object so that it has the same velocity as the player when it is created. However, when I try to implement this, it always spawns immobile, even when the player is moving. Yet, my attempt at debugging shows the player velocity and the instantiated object's velocities as being the same. (???)
void Update()
{
if(Input.GetKeyDown(KeyCode.Space))
{
Instantiate(shot, playerPos.position, playerPos.rotation);
shot.GetComponent<Rigidbody>().velocity = GetComponent<Rigidbody>().velocity;
Debug.Log("Shot " + shot.GetComponent<Rigidbody>().velocity + " // Sled " + GetComponent<Rigidbody>().velocity);
}
}
Comment
Best Answer
Answer by Eyes-Wide-Shut · Apr 24, 2019 at 03:59 AM
You need to reference the Instantiated object's Rigidbody, not the prefab's.
GameObject shotInstance = Instantiate(shot, playerPos.position, playerPos.rotation);
shotInstance.GetComponent<Rigidbody>().velocity = GetComponent<Rigidbody>().velocity;
Amazing, thanks! I thought Prefabs were completely static at runtime (given the name); not sure I'd have ever arrived at that solution.