Search Unity

Correct way to spawn prefab with wanted rotation

Discussion in 'Scripting' started by Censureret, Aug 23, 2021.

  1. Censureret

    Censureret

    Joined:
    Jan 3, 2017
    Posts:
    363
    So i have the following prefab:

    upload_2021-8-23_23-27-20.png

    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:
    Code (CSharp):
    1. Instantiate(WeaponPrefab, WeaponPosition.position,
    2.                     WeaponPrefab.Transform.rotation, WeaponPosition);
    However the rotation is completely off when it is spawned giving me this:

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

    So what is the correct way of spawning these things?
     
  2. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    11,847
    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:
    Code (csharp):
    1. GameObject newWeapon = Instantiate(WeaponPrefab);
    2. newWeapon.transform.parent = mountPoint.transform;
    3. newWeapon.transform.position = mountPoint.transform.position;
    4. newWeapon.transform.rotation = mountPoint.transform.rotation;
     
    Last edited: Aug 23, 2021
    Kurt-Dekker likes this.
  3. Censureret

    Censureret

    Joined:
    Jan 3, 2017
    Posts:
    363
    Thhank you that helped alot! :D
     
    Joe-Censored likes this.
  4. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,686
    You can even shorten that to parent it and zero everything out at once:

    Code (csharp):
    1. GameObject newWeapon = Instantiate<GameObject>(WeaponPrefab, mountPoint.transform);
    Second argument is the Transform to parent it to.
     
    Joe-Censored likes this.