Change rotation of a gameobject, so that its child has same global rotation as another gameobject.

I have 3 game objects in a scene:

–Scene
----GameObject1
----GameObject2
-------GameObject3(child of GameObject2)

Each of those game objects has some random rotation.

I need to rotate the GameObject2 in such way where global (not local) rotation of the GameObject3 is identical to the rotation of the GameObject1. (As in achieve state where: if(GameObject1.transform.rotation == GameObject3.transform.rotation) is true)

The local rotation of the GameObject3 cannot be changed in any way at all, all rotation changes are done to the GameObject2.

Thank you.

Have you tried checking the GameObject1.transform.localRotation?

Nope, that value is of no use in this problem.

Sorry I misread your question.

Perhaps this may be of some use to you?

That merely gives me an angle in degrees between two rotations, which is of no use for the thing i need.

Hm. I think this will inherently have issues because you want to adjust and check the rotation of a child object. Sorry for not having a solution!

EDIT:

This might be of use?

What you need to do is get the quaternion that represents the rotation from the child object (gameObject3) to your target object (gameObject1). Then you apply that rotation to gameObject2. That will look something like this:

Edit: I realized that this doesn’t account for gameObject2’s rotation. The above would only work if gameObject2’s rotation was zero (Quaternion.identity). But since we’re changing it’s rotation to whatever we need anyway, the simple fix is to just clear it before we do our calculations!

gameObject2.transform.rotation = Quaternion.identity;
Quaternion rot = gameObject1.transform.rotation * Quaternion.Inverse(gameObject3.transform.rotation);
gameObject2.transform.rotation *= rot;