Parenting object changes position of it

I’m trying to unparent an object without changing the position. I’ve tried using SetParent with worldPositionStays set to true as a parameter, and I’ve even tried this:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Guard : MonoBehaviour
{
    public Transform gun;

    private void Start()
    {
        Vector3 gunPos = gun.position;
        Quaternion gunRot = gun.rotation;
        gun.SetParent(null, true);
        gun.position = gunPos;
        gun.rotation = gunRot;
    }
}

and it hasn’t worked. What’s going on here?

Turns out it was working, but when it unparented, it was in the wrong position.