Skip to main content
3 of 6
added 125 characters in body
Object
  • 289
  • 1
  • 6
  • 13

How to make a hit obejct do something when hit by raycast from player

INTRODUCTION:

In unity, I want to make a dynamic, object use system. Where the main player camera shoots a raycast when left mouse button is clicked and if the raycast from the player hits an object with a tag "use" then that object will do whatever its function is, in the chairs case it would disable the player controller and camera and enable its own camera.

CODE:

This is the main use script which is responsible for shooting the raycast from the player camera:

public interface IPlayerUsable
{
    public void Use();
}
public class use : MonoBehaviour
{
    public Camera cam; //player camera

    void Update()
    {
        if (Input.GetKey(KeyCode.Mouse0) == true) //when left click down
        {
            RaycastHit hit;
            Ray ray = cam.ScreenPointToRay(Input.mousePosition); // shoot raycast from camera mouse (its locked so its center)

            if (Physics.Raycast(ray, out hit, 10.0f)) // shoots raycast a distance of 10
            {
                if (hit.collider.TryGetComponent(out IPlayerUsable usable)) // im not sure what this really means but I would assume it detects the public interface component of the object it hit
                {
                    usable.Use(); // it runs the function of the objects public interface
                    Debug.Log("Shot a ray"); // tells you if it did it
                }
             
            }
        }
 
    }
}

This is the initiator script on the object that can be used (the chair in this example):

public class PerspectiveChange : MonoBehaviour, IPlayerUsable
{
    public GameObject Player; // the player controller
    public GameObject chaircam; // the chair camera controller
    private bool beingused = false; //is obejct being used?

    public void Use()
    {
        Debug.Log("I was hit by a Ray"); //tells the console if it recieved the hit
        beingused = true; // is beingused
        chaircam.gameObject.SetActive(true); //shows the chair camera
        Player.gameObject.SetActive(false); //disables the player controller and camera
    }
}

The scene is this: A quick description of what is going on; chair1 is the gameobject with the initiator script and has no colliders on it but is the parent of 2 colliders that are convex. FPSPlayer is the player controller, Playercam is the camera that shoots the main player camera shoot script. If you need any more information feel free to ask and I will provide it in an edit.

enter image description here

CONCLUSION:

My goal is to make an object do what it does if it has the tag "use" when it is hit by a left click triggered raycast from the player camera

Object
  • 289
  • 1
  • 6
  • 13