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 thean object that can be used for example a chair is hit by that specific raycast specifically from the player hits an object with a tag "use"(there could be other raycasts being shot out from other objects and the player), then that object will do whatever its function isrun its action, in the chairs case it would disable the player controller and camera and enable its own camera.
This is the main use script which is responsible for shooting the raycast from the player camera shoot script:
public interface IPlayerUsable
{
public void Use();
}
public class use : MonoBehaviour
{
public Camera cam; //player camera
void Update()
{
if (Input.GetKey(KeyCode.Mouse0) == true) //whenif left clickmouse button down
{
RaycastHit hit;
Ray ray = cam.ScreenPointToRay(Input.mousePosition); // shootshoots raycast from camera mouse position (itscursor lockmode is locked so its center)
from centre of screen)
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 assumenothing itmore detectsneeded thehere, publicits interfacenow componentup ofto the object it hit
{
usable.Use(); // it runs the functionto ofdo the objects public interface
Debug.Log("Shot a ray"); // tells you if itaction didonce it
}
detects }this
}
}
}
public class PerspectiveChange : MonoBehaviour, IPlayerUsable
{
private publicvoid HitByRay(GameObject Player;gameObject) //detects thea playerraycast controllerhitting itself
{
publicif(gameObject.name GameObject== chaircam;"Playercam") // the chair camera controller
private booldetects beingusedif =the false;raycast //is obejct beingfrom used?
camera
public void Use(){
{
//does the action Debug.Log("Ithis wascan hitalso byjust activate a Ray");boolean //tellsso the consoleaction ifcan itoccur recievedin thea hitdifferent void):
beingused = true; // is beingused
chaircam.gameObject.SetActive(true); //shows the chair camera
Player.gameObject.SetActive(false);
//disables the player controller and camera Debug.Log("I was hit by a Ray");
}
}
My goal is to make an object do what it does if it hasbe able to detect the tag "use" when it is hit by a left click triggered raycast that is being shot from the player camera. However,an object and detect the objects name that shot out that raycast and if that name is not being sent in the codename we want then it does something.