How to find the closest point outside a collider from a point inside the collider.

I’m trying to figure out how to reposition a transform that is inside a object with a collider to the nearest position just outside of the collider.

I have been trying to use these 3 methods I’ve found:

        //Method 1
        Vector3 closestPoint = avoidanceObject.GetComponent<Collider>().ClosestPoint(target.transform.position);

        //Method 2
        Vector3 closestPointInBounds = avoidanceObject.GetComponent<Collider>().ClosestPointOnBounds(target.transform.position);

        //Method 3
        Vector3 pos = target.transform.position;
        Quaternion rot = target.transform.rotation;
        Vector3 closestPointCollider = Physics.ClosestPoint(target.transform.position, target.GetComponent<Collider>(), pos, rot);

        target.transform.position = closestPointCollider;

These three methods do not change the position, is it because the transform is inside the collider? If so how would I find the nearest point or direction to move outside of the collider?

Thank you!

You can try with “Physics.OverlapSphere”

I use a code like this to detect an enemy inside of the radius of a bomb explosion:

public float radius = 200f;

void Explosion()
    {   
        Collider[] colliders = Physics.OverlapSphere(transform.position, radius);
        foreach(Collider enemy in colliders)
        {
            if(enemy.CompareTag("Enemy"))
            {
                EnemyBehaviour exploded = enemy.GetComponent<EnemyBehaviour>();
                exploded.DestroyedByBomb();
                Destroy(gameObject);
            }
        }
    }
}

and you can Make something like this:

public float radius = 200f;
public GameObject yourObject;

public void DetectNewPosition()
    {   
        Collider[] colliders = Physics.OverlapSphere(transform.position, radius);
        foreach(Collider newPos in colliders)
        {
            if(newPos.CompareTag("NearestPoint"))
            {
                yourObject.transform.Position = newPos.transform.Position;
            }
        }
    }
}

This requires that your “Nearest Point” object have a collider and a tag “NearestPoint”

Another option is to use “OnCollisionEnter” like this:

public GameObject yourObject;

private void OnCollisionEnter(Collision collision1)
    {
        //Debug.Log("Colision");
        if (collision1.collider.tag == "NearestPoint")
        {
            NewPos();
        }
		
        void NewPos()
        {
            ContactPoint contact = collision1.GetContact(0); //contacts[0];
            Quaternion qua = Quaternion.FromToRotation(Vector3.up, contact.normal);
            Vector3 pos = contact.point;

            yourObject.transform.position = pos;
			yourObject.transform.rotation = qua;
        }
    }