Vetuka
Vetuka

Reputation: 1651

How to change object's pivot point using C# in Unity?

I am trying to change the Pivot Point of an object in Unity 3D using C#.

I am aware of editing the object in a design software beforehand to desired point but, in my specific situation, the Pivot Point needs to be changed while game in running.

Here is the code I am using to rotate the object from its left side:

    verticalInputLeft = Input.GetAxis("VerticalLeft");       

    rotationLeftX += verticalInputLeft * verticalSensitivity * Time.deltaTime;
    rotationLeftX = Mathf.Clamp(rotationLeftX, minAngle, maxAngle);

    transform.localEulerAngles = new Vector3(rotationLeftX, transform.localEulerAngles.y, transform.localEulerAngles.z);

I would like to use same method to apply rotation from right side. For that, I need to change the pivot point of the object while game is running.

Thank you.

Upvotes: 2

Views: 5979

Answers (2)

Natalia S.
Natalia S.

Reputation: 59

Actually, there is a way to change pivots.

If you take the RectTransform component directly, you could change the pivot's value and other attributes related to the screen's position.

Example:

this.gameObject.GetComponent<RectTransform>().pivot = new Vector2(0.5f, 0.5f);
//Center the pivot

Upvotes: 5

vasmos
vasmos

Reputation: 2586

There is no way to change pivots directly,

Workaround, create an empty game object(s) in position of where you want your new pivot and set the parent transform to this game object.

gameObject.transform.SetParent(pivotGameObject);

to remove parent

gameObject.transform.SetParent(null);

Upvotes: 4

Related Questions