You need to create a simple but functional interaction system using a raycast.
The player controls a first-person camera, aims a crosshair (center of the screen) at interactive objects, and interacts with them using the E key.
- Ray from camera center — every time
Eis pressed, cast a ray from the screen center (as in shooters). - LayerMask — the ray must interact only with objects on the
"Interactable"layer. All other objects (walls, floor, triggers) are ignored. - RaycastHit — upon a hit, the ray must:
- Get the
IInteractablecomponent from the object. - Call the
Interact()method. - Print to the console:
"Interacted with {object name} at distance {distance}".
- Get the
- Visualization — draw the ray using
Debug.DrawRay:- Green on hit (duration 0.5 sec).
- Red on miss (duration 0.5 sec).
- IInteractable interface — implement it in two types of objects:
Door(door): opens/closes (any logic:Debug.Logor animation).LightSwitch(switch): turns the light on/off (changes the intensity of a point light).
// IInteractable.cs
public interface IInteractable
{
void Interact();
}
// Interactor.cs (attached to the camera)
public class Interactor : MonoBehaviour
{
public float maxDistance = 5f;
public LayerMask interactableLayer; // Assign the "Interactable" layer in the Inspector
void Update()
{
if (Input.GetKeyDown(KeyCode.E))
{
CastInteractionRay();
}
}
void CastInteractionRay()
{
// 1. Create a ray from the center of the screen
// 2. Raycast with LayerMask
// 3. If hit — get IInteractable and call Interact()
// 4. Debug.DrawRay (green/red)
}
}
// Door.cs
public class Door : MonoBehaviour, IInteractable
{
private bool isOpen = false;
public void Interact()
{
isOpen = !isOpen;
Debug.Log($"Door is {(isOpen ? "open" : "closed")}");
// Additional: rotate the door, play sound, etc.
}
}
// LightSwitch.cs
public class LightSwitch : MonoBehaviour, IInteractable
{
public Light targetLight;
private bool isOn = true;
public void Interact()
{
isOn = !isOn;
targetLight.intensity = isOn ? 1f : 0f;
Debug.Log($"Light is {(isOn ? "on" : "off")}");
}
}- Create a scene: floor, walls, camera (FPS controller).
- Add two cubes: one as
Door, the second asLightSwitch. - Assign them the
"Interactable"layer. - Attach the appropriate scripts (
Door,LightSwitch) and set up references. - Run the scene, aim at the objects (crosshair in the center of the screen) and press
E. - Check the console and ray visualization in the Scene View.
- Add highlighting to the object the crosshair is over (change material or add an Outline).
- Implement interaction sound (
AudioSource.PlayOneShot). - Make
IInteractablehave astring InteractionPromptproperty (e.g.,"Press E to open the door") and display it on the UI.
- Solution files
- FPS controller
- Put the MainCamera in the GameObject "Player"
- Assign the PlayerCameraRotation.cs script to MainCamera
- Assign the PlayerMovement.cs script to Player
Warning
The solution uses the new Input System Package available in Unity 6+