Press to connect

Hello, this code shows that on collision, it will grab the other rigid body and add a fixed joint to connect them.

I would like to press E to connect them instead of on collision.

How would I do that ?

void OnCollisionEnter(Collision collision)
{
    if (collision.gameObject.GetComponent<Rigidbody>() != null && !hasJoint)
    {
        gameObject.AddComponent<FixedJoint>();
        gameObject.GetComponent<FixedJoint>().connectedBody = collision.rigidbody     
        hasJoint = true;
    }
}

I am assuming that when the player presses the E key, it shoud only connect the bodies if they are actually touching.

Note: I haven’t tested the code because I do not have Unity on this computer.

// Keep this as "public" so you can monitor it in the Inspector.
// When you're done testing, change it to "private".
public Rigidbody otherRigidbody;

void OnCollisionEnter(Collision collision)
{
    if (otherRigidbody == null)
        otherRigidbody = collision.rigidbody;
        
    // The purpose of the if-statement:
    // If the player touches object 1
    // then object 2 bumps into the player
    // then the player presses the key to connect the bodies
    // it will connect object 1, not object 2.

    // If you wish to connect the object that most recently touched the player
    // then remove the if-statement.
}

void OnCollisionExit(Collision collision)
{
    if (otherRigidbody == collision.rigidbody)
        otherRigidbody = null;
}

void Update()
{
    if (Input.GetKeyDown(KeyCode.E))
    {
        bool justConnected = ConnectBody();
        Debug.Log("Just connected: " + (justConnected ? "Yes" : "No"));
    }

    if (Input.GetKeyDown(KeyCode.F))
    {
        DisconnectBody();
    }
}

bool ConnectBody ()
{
    if (otherRigidbody != null && !hasJoint)
    {
        var fixedJoint = gameObject.AddComponent<FixedJoint>();
        fixedJoint.connectedBody = otherRigidbody;
        hasJoint = true;
        return true;
    }
    else
    {
        return false;
    }
}

void DisconnectBody ()
{
    if (hasJoint)
    {
        var fixedJoint = gameObject.GetComponent<FixedJoint>();
        if (fixedJoint != null)
            Destroy(fixedJoint);
    
        hasJoint = false;
        otherRigidbody = null;
    }
}