Grabbing script error

Hello, i made an script for simple grabbing, but the grabbed object can go into other collisions, and i dont know what to do, also i couldt find any solution to make it so i can rotate the object while holding right click. Please, help somebody.

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

public class ObjectInteraction : MonoBehaviour
{
    [SerializeField] Camera cam;
    [SerializeField] float maxGrabDistance = 10f, throwForce = 20f;
    public float lerpSpeed = 10f; // Changed to public
    [SerializeField] Transform objectHolder;

    Rigidbody grabbedRB;

    void Update()
    {
        if (grabbedRB)
        {
            grabbedRB.MovePosition(Vector3.Lerp(grabbedRB.position, objectHolder.transform.position, Time.deltaTime * lerpSpeed));

            if (Input.GetMouseButtonDown(0))
            {
                grabbedRB.isKinematic = false;
                grabbedRB.AddForce(cam.transform.forward * throwForce, ForceMode.VelocityChange);
                grabbedRB = null;
            }
        }

        if (Input.GetKeyDown(KeyCode.E))
        {
            if (grabbedRB)
            {
                grabbedRB.isKinematic = false;
                grabbedRB = null;
            }
            else
            {
                RaycastHit hit;
                Ray ray = cam.ViewportPointToRay(new Vector3(0.5f, 0.5f));
                if (Physics.Raycast(ray, out hit, maxGrabDistance))
                {
                    grabbedRB = hit.collider.gameObject.GetComponent<Rigidbody>();
                    if (grabbedRB)
                    {
                        grabbedRB.isKinematic = true;
                    }
                }
            }
        }
    }
}

Rigidbody is for physics, it’s natural for it that he interacts with other physical objects and colliders. You can solve the problem in two ways.

  • Your object doesn’t have to be a Rigidbody so you can use game objects with Collider only.
  • Your object has to use Rigidbody so you can turn it off in time of dragging. All functions on time of dragging must know that you dragging it (some kind of bool duringDrag), and when you release the object it turns on Rigidbody again. You do all operations on Collider with trigger only.

Edit: Sorry you probably asked for something else, my bad.

Hi so, i tried making rigidbody disable when im grabbing the object, but that didnt quite work. But still, thanks for help

You must change the whole concept because you doing drag and drop on a Rigidbody component. If you turn off Rigidbody it just won’t work.

Look at Collider functions (you need a trigger on) like OnMouseDown (link).