Lookat() while keeping parent rotation

So Im currently making a turret for a spaceship(1), I want the turret(2) to only spin on the y-axis to look at its target(3).
7455152--914708--upload_2021-8-27_22-4-16.png
Everything works so far but the turret(2) has to spin along with the spaceship(1) when it turns or rotates.
7455152--914711--upload_2021-8-27_22-5-35.png
When the spaceship(1) rotates on the x-axis the turret(1) doesnt continue looking at its target and instead has some kind of offset applied. I don’t understand why its doing this especially when ive set the turrets(2) X-axis rotation to its parents(1).

The code ive used is below

public Vector3 lookPos;
public Quaternion lookRot;
public float euler;
public Quaternion rotation;

lookPos = target.transform.position - this.transform.position;
lookRot = Quaternion.LookRotation(lookPos, Vector3.forward);
euler = lookRot.eulerAngles.y;

rotation = Quaternion.Euler(0, euler, 0);

this.transform.rotation = rotation;

this.transform.localEulerAngles = new Vector3(
this.transform.parent.transform.localEulerAngles.x,
this.transform.localEulerAngles.y,
this.transform.parent.transform.localEulerAngles.z);

First, welcome to the unity forum.

Second, if you post code please use code tags (a how-to post is pinned). Here, I’ll show you how your code will look like:

public Vector3 lookPos;
public Quaternion lookRot;
public float euler;
public Quaternion rotation;

lookPos = target.transform.position - this.transform.position;
lookRot = Quaternion.LookRotation(lookPos, Vector3.forward);
euler = lookRot.eulerAngles.y;

rotation = Quaternion.Euler(0, euler, 0);

this.transform.rotation = rotation;

this.transform.localEulerAngles = new Vector3(
this.transform.parent.transform.localEulerAngles.x,
this.transform.localEulerAngles.y,
this.transform.parent.transform.localEulerAngles.z);

Now to your problem. There is a handy function which does exactly what you want: Unity - Scripting API: Transform.LookAt

Happy coding!