Correct way to spawn prefab with wanted rotation

So i have the following prefab:

As you can see ive saved it with a transform that i have referenced in my script.

So when i spawn this i use the following code:

Instantiate(WeaponPrefab, WeaponPosition.position,
                    WeaponPrefab.Transform.rotation, WeaponPosition);

However the rotation is completely off when it is spawned giving me this:

7442957--912458--upload_2021-8-23_23-30-30.png

So what is the correct way of spawning these things?

You’re providing the prefab’s own rotation as the rotation to set, and you’re making it a child of another object. The rotation shown for the instantiated object will report in relation to its parent in the inspector (local rotation, not world rotation). Usually you would want to set the rotation to something that exists in the game world already, not against a prefab in the asset’s folder.

If this is something like a gun being mounted to an arm, I’d set an empty GameObject to act as a mount. Then when you instantiate you set the mount point as the parent, and just zero out the instantiated object’s local position and local rotation (or just set them to the mount point’s world position and world rotation).

Something like this:

GameObject newWeapon = Instantiate(WeaponPrefab);
newWeapon.transform.parent = mountPoint.transform;
newWeapon.transform.position = mountPoint.transform.position;
newWeapon.transform.rotation = mountPoint.transform.rotation;
1 Like

Thhank you that helped alot! :smile:

1 Like

You can even shorten that to parent it and zero everything out at once:

GameObject newWeapon = Instantiate<GameObject>(WeaponPrefab, mountPoint.transform);

Second argument is the Transform to parent it to.

1 Like