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 an object that can be used for example a chair is hit by that specific raycast specifically from the player (there could be other raycasts being shot out from other objects and the player), then that object will run its action, in the chairs case it would disable the player controller and camera and enable its own camera.
CODE:
This is the main player camera shoot script:
public Camera cam;
void Update()
{
if (Input.GetKey(KeyCode.Mouse0) == true) //if left mouse button down
{
RaycastHit hit;
Ray ray = cam.ScreenPointToRay(Input.mousePosition); //shoots raycast from mouse position (cursor lockmode is locked so its from centre of screen)
if (Physics.Raycast(ray, out hit, 10.0f)) // shoots raycast
{
//nothing more needed here, its now up to the object to do the action once it detects this
}
}
}
This is the initiator script on the object that can be used (the chair in this example):
private void HitByRay(GameObject gameObject) //detects a raycast hitting itself
{
if(gameObject.name == "Playercam") //detects if the raycast is from camera
{
//does the action (this can also just activate a boolean so the action can occur in a different void):
beingused = true;
chaircam.gameObject.SetActive(true);
Player.gameObject.SetActive(false);
Debug.Log("I was hit by a Ray");
}
}
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.
CONCLUSION:
My goal is to be able to detect the raycast that is being shot from an object and detect the objects name that shot out that raycast and if that name is the name we want then it does something.