Skip to content

Instantly share code, notes, and snippets.

@mrowdy
Last active May 23, 2019 06:56
Show Gist options
  • Save mrowdy/a0e93bfb17659eb8229a97fd47d7f15c to your computer and use it in GitHub Desktop.
Save mrowdy/a0e93bfb17659eb8229a97fd47d7f15c to your computer and use it in GitHub Desktop.
Rotate by pivot inside Unity editor
using UnityEngine;
public class RotationPivot: MonoBehaviour
{
/**
* The transform of the object you want to rotate with this pivot
*/
public Transform target;
public void SetRotation(Quaternion newRotation)
{
//We store current parents of pivot and target
Transform oldPivotParent = transform.parent;
Transform oldTargetParent = target.transform.parent;
RemoveParents();
//Set the pivot as the parent of target
target.transform.SetParent(transform);
//Apply new rotation to pivot. Target follows since it has the pivot as parent now
transform.rotation = newRotation;
RemoveParents();
transform.SetParent(oldPivotParent);
target.transform.SetParent(oldTargetParent);
}
/*
* Reset parent of target and pivot. We need this to make both switchable
*/
private void RemoveParents()
{
target.transform.SetParent(null);
transform.SetParent(null);
}
}
using UnityEditor;
using UnityEngine;
/**
* Custom editor for RotationPivot
*/
[CustomEditor(typeof(RotationPivot))]
public class RotationPivotEditor : Editor {
/**
* Gets called everytime the scene GUI is redrawn. Only if the gameObject is slected in the inspector
*/
void OnSceneGUI()
{
//The RotationPivot component of the selected game object
RotationPivot rotationPivot = (RotationPivot)target;
//Return if rotationPivot has no target
if(rotationPivot.target == null)
{
return;
}
//Display a RotationHandle with the position and rotation of rotationPivot and store its value inside newRotation
Quaternion newRoation = Handles.RotationHandle(
rotationPivot.transform.rotation,
rotationPivot.transform.position
);
//Continue only if the new rotation differs from the current rotation
if (newRoation != rotationPivot.transform.rotation)
{
//Register a undo action both on the rotationPivot and its target
Undo.RecordObject(rotationPivot.transform, "Rotate by pivot");
Undo.RecordObject(rotationPivot.target, "Rotate by pivot");
//Apply the new rotation
rotationPivot.SetRotation(newRoation);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment