Instantiating physics objects

Is there some trick to instantiating physics objects? I have a prefab with a rigidbody and box collider on it, and I’m trying to spawn the objects on tap. If I use the prefab directly in the scene, it works fine, but the instances that are created at runtime aren’t getting gravity applied

Original Post on Discord

by user 401167615826984963

Can you compare it to the physics cannon sample?

It spawns rigidbody prefabs too

Thanks for pointing me there. It’s working in that case, but I’m still having trouble creating my own from scratch. There seem to be multiple ways of instantiating objects, which might be the problem. However, I can’t get the example code working in my sandbox project. It complains about incorrect types.

Here’s how I am able to instantiate objects and have them appear in the scene, but without physics

const instance = await this.myPrefab?.instantiate()
instance?.position.set(p.x, p.y, p.z)

But in the example code, the instantiation happens like this:

const opts = new InstantiateOptions()
opts.position = p
const instance = GameObject.instantiate(this.prefab, opts)

by user 401167615826984963

Argument of type ‘Object3D | undefined’ is not assignable to parameter of type ‘Object3D | GameObject | null’.
Type ‘undefined’ is not assignable to type ‘Object3D | GameObject | null’.ts(2345)

by user 401167615826984963

ok, so I got the second method working by assigning the prefab to an object in the scene, as opposed to an actual prefab asset

by user 401167615826984963

Where is that from?

When its a prefab asset its exported as a separate glb and therefore loaded via e.g. an AssetReference type. That should work the same with physics but i can try to reproduce it after the holidays if you say it does not

It’s from the Cannon.ts script in the cannon playground project

by user 401167615826984963

I’ll keep playing around with it and update this thread if I find a solution

by user 401167615826984963

Thanks!

My initial guess was the correct way of doing it, but there was some issue with the code watcher and it wasn’t fully regenerating the c# stub, so the assigned asset reference was null (I think I renamed the serializable field at some point)

by user 401167615826984963

by user 401167615826984963

Which was the initial guess? Good to hear you got it going

const instance = await this.myPrefab?.instantiate()
instance?.position.set(p.x, p.y, p.z)

by user 401167615826984963