Instantiated prefab has the wrong rotation.

I’m having an issue where a gun prefab I’m using is being instantiated wrong when the player prefab is loaded.

When I drag in the player prefab manually and drag the gun prefab in manually it shows the correct orientation of the gun ( at the bottom right of the player’s camera view). However, when I instantiate the gun prefab automatically with the player prefab it causes the gun prefab to be rotated 90 degrees in the x direction either positively or negatively, depending on a few factors I’m unsure of at this point.

The hierarchy of the player with the gun instantiated is: -player prefab -controller -playerCamera -gun prefab -gun model 1 -gun model 2 …etc

The player, controller, playerCamera and gun prefab objects all have position (0,0,0) and rotation (0,0,0).

This is the code that is instantiating the gun prefab:

GameObject tempGun = (GameObject)Instantiate (smg, cameraTransform.transform.position+smg.transform.position, smg.transform.rotation);
tempGun.transform.parent = cameraTransform;

So here I am instantiating the gun and then setting the guns parent as the playerCamera as shown above in the hierarchy.

One fix I found is to set the rotation of the gun in the gun scripts update function to add an additional 90 degrees in the x direction but the problem with this is that when i switch guns, the gun travels really quickly from the initial position before rotating it…it looks really ugly so I would rather not do that.

If you need any more code I’m happy to supply it, thanks.

First of all, you’re giving the tempGun object the smg prefab’s rotation, yes? This means that if the smg’s rotation is (0,0,0) the tempGun will have (0,0,0) GLOBAL rotation. This means that whatever direction the gun points to when it is not parented to anything will be the rotation. You’ll have to use the LOCAL rotations.

Couple of things you can try.

Set rotation of object to the parent’s rotation on instantiate:

GameObject tempGun = (GameObject)Instantiate (smg, cameraTransform.transform.position+smg.transform.position, cameraTransform.rotation);

Reset its local rotation after parenting it:

tempGun.transform.parent = cameraTransform;
tempGun.transform.localRotation = Quaternion.identity;

Hope this helps.

Other simple way to solve this issue without creating empty parent game object:

GameObject pc = (GameObject) Instantiate (Prefab, position, rotation, transform);
pc.transform.Rotate (new Vector3(rotationWished.x,rotationWished.y,rotationWished.z));

Where you choose in Vector3 rotationWished which rotation you want.