// Clears any currently selected object and calls on exit if there is one. private void ClearCurrentObject() { // Check if there's a current object. if (currentRaycastObject != null) { // If so, call OnExit on that object and clear the variable. currentRaycastObject.OnRaycastExit(); currentRaycastObject = null; } }
// Performs the raycast and affects any raycasted objects. public void ProcessRaycast() { // Set the origin of the raycast line renderer. raycastLine.SetPosition(0, transform.position); // Create a ray to raycast with. Ray raycastRay = new Ray(transform.position, transform.forward); // Variable to store the result of the raycast. RaycastHit hitInfo; // Show a debug line in the editor. Debug.DrawRay(raycastRay.origin, raycastRay.direction); // Do the raycast and store the result in hitInfo. if (Physics.Raycast(raycastRay, out hitInfo)) { // If we hit something, update the raycast to end at that object. raycastLine.SetPosition(1, hitInfo.point); // Store the hit object. GameObject hitObj = hitInfo.collider.gameObject; // Get the raycast interactable script from the object (if it has one). RaycastInteractableObject gazeObj = hitObj.GetComponent <RaycastInteractableObject>(); // If it does have the interactable script, interact with the object. if (gazeObj != null) { // Update the raycast hit color. SetRaycastColor(raycastHitColor); // If we aren't looking at the same object as last frame, update the past/present objects. if (gazeObj != currentRaycastObject) { // Clear the previous object. ClearCurrentObject(); // Set the new object. currentRaycastObject = gazeObj; // Call OnEnter. currentRaycastObject.OnRaycastEnter(hitInfo); } // If we ARE looking at the same object, just call it's OnRaycast() function. else { // Call the hold function. currentRaycastObject.OnRaycast(hitInfo); } } // If we aren't looking at a valid interactable object, clear the previous object. else { // Clear previous object. ClearCurrentObject(); } } // If we aren't looking at any physics object, clear previous object and update line renderer. else { // Make line renderer stretch out to infinity (kinda). raycastLine.SetPosition(1, transform.forward * 1000.0f); SetRaycastColor(raycastMissColor); // Clear any active object, if there is one. ClearCurrentObject(); } // Check for user input. CheckForInput(hitInfo); }