# Attach Transform to another GameObject

The scenario I am trying to accomplish is attaching a turret to a mount point on a ship. I have gotten as far as bringing in the prefab and assigning it as a child object with the following code:

GameObject leftFixedGun = (GameObject)MonoBehaviour.Instantiate(Resources.Load("Laser Fixed Gun"), leftMountPoint.position, leftMountPoint.rotation);
leftFixedGun.transform.parent = player.transform;


The problem is, it takes on the rotation of the mount point object, obviously, which isn't exactly what I'm going for.

I have a couple ideas of how to fix this problem, but would really like it to be a different solution all together.

My idea to fix this problem would be to rotate the transform at leftGunMountPoint in order to align the attached gun correctly.

The ideal solution, and the one I would like help with, would to be to align a local mountPoint transform I have under the leftFixedGun to a leftGunMountPoint under the ship I am trying to attach the gun to.

Thanks!

EDIT:

• Create a transform, and line it up with where you want to place the item trying to be mounted.
• The following code attached the gun as I wanted.

GameObject laserFixedGun = (GameObject)MonoBehaviour.Instantiate(Resources.Load("Laser Fixed Gun"), leftMountPoint.position, leftMountPoint.rotation); laserFixedGun.transform.parent = player.transform;

If I'm reading your question correctly, it sounds like you have a locator Transform for a point relative to the ship where you'd like to mount your turret. But if you attach it and fix the rotation to match the ship, then your gun is rotated the wrong way from how you had it when you made the prefab?

If that is indeed the case, the solution is to add another top-level GameObject to your "Laser Fixed Gun" prefab that you expect to parent to the ship, matching both the rotation and position like you have it.

But then within that prefab, the actual LaserFixedGun objects will be rotated in such a way that they look correct.

Assuming your prefab looks something like this:

v Laser Fixed Gun [ Transform, MeshRenderer, TurretScript]
> Thrusters [ Transform, ParticleSystem ]


You'll want to change it to this:

v Laser Fixed Gun [ Transform ]
v Laser Fixed Gun [ Transform, MeshRenderer, TurretScript]
> Thrusters [ Transform, ParticleSystem ]


Using a child object in your mount point is possible but unintuitive with a transform hierarchy. Treating your top-level object as your mount point will make your life much easier.

• Excellent, knew there was a better way to do this, now to just move it relative to the parent transform. – dardo Apr 21 '13 at 4:07
• Wish I could upvote you more than once =) Loving Unity so far. – dardo Apr 21 '13 at 4:27