Object being instantiated with a random a random rotation even when told not to?

I am instantiating an object, at the target position. When I do so, it creates it with a random rotation, for no reason at all. I have tried these things:

Setting it’s rotation to be 0 on all axis’ after it has been created, I’ve tried making a quaternion which will make the objects rotation 0 on all axis’ as the rotation value of the instantiate function, I’ve tried to edit the objects rotation in the inspector and in Blender, but nothing happens.

Code:

GameObject object = (GameObject)Instantiate(objectToMake, objectSpawn.position, Quaternion.identity);

//parentObject is a gun attached to the player.

object.transform.SetParent(parentObject.transform) //this is so the object stays on the gun at all times.

What’s wrong with this code? If you need anymore info, please ask. this is driving me insane!

What is the rotation of the parentObject? It will inherit this once its parented to it.

Sorry for the late reply! The parent object, which is the gun, it's rotation on all axis' is zero. The players rotation, as well as the camera, are all zero. One thing I forgot to mention is that it randomizes the rotation each time it's instantiated; so one time it may be 10, 6, 3(x, y, z), and another time it may be 27, 19, 8(x, y, z). I have no other code effecting the rotation, and the object's rotation is set to 0, 0, 0, in Unity and in Blender.

Try setting the localRotation quaternion to identity after you parent the object. I think it may be interpreting the instantiated transform as it relates to the parent object.

I mean, Line 17 is missing. You say the error happen on line 17, but there is only 12 lines of code pasted here. How would we know which one is Line 17? <img src="https://dl.dropboxusercontent.com/u/86837997/answers-images/Line17Missing.png">

1 Answer

1

Is any gameObject in the parent chain animated? it could be zero when not playing however when it is animating, rotations might be happening. the safest bet is that when you instantiate it you can have it match the rotation of the soon to be parent as it is instantiated then attach it to the parent:

  GameObject obj = Instantiate(objectToMake, objectSpawn.position, parentObject.transform.rotation) as GameObject;
     
     //parentObject is a gun attached to the player.
     
     obj.transform.parent = parentObject.transform;
     //this is so the object stays on the gun at all times.

It did work the first time, but it seems to still rotate it randomly. For now I'll just use objects under the gun and enable them instead of instantiated them. Thanks, though!

oh shit hang on