-
Notifications
You must be signed in to change notification settings - Fork 3
/
InteractWithSelectedObject.cs
61 lines (54 loc) · 1.89 KB
/
InteractWithSelectedObject.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// Script needed to detect and interact with the object selected by raycast.
/// Attached to the MainCamera, child of the RigidbodyFPS.
/// </summary>
public class InteractWithSelectedObject : MonoBehaviour
{
private IInteractable objectToInteractWith; // reference pointing to the object best suitable for interaction
private void OnEnable()
{
SphereRaycast.ObjectToInteractWithChanged += OnObjectToInteractWithChanged;
SphereRaycast2.ObjectToInteractWithChanged += OnObjectToInteractWithChanged;
}
private void OnDisable()
{
SphereRaycast.ObjectToInteractWithChanged -= OnObjectToInteractWithChanged;
SphereRaycast2.ObjectToInteractWithChanged -= OnObjectToInteractWithChanged;
}
private void Update()
{
if (Input.GetButtonDown("Interact"))
CheckForInteractionInput();
#if UNITY_EDITOR
if (objectToInteractWith != null)
Debug.DrawRay(this.transform.position, ((MonoBehaviour)objectToInteractWith).transform.position - this.transform.position, Color.green);
#endif
}
/// <summary>
/// Called when Object To Interact With changes in the DetectInteractableObject
/// script through an event.
/// </summary>
public void OnObjectToInteractWithChanged(IInteractable returnedInteractable)
{
objectToInteractWith = returnedInteractable;
}
/// <summary>
/// checks if objectToInteractWith is not null then if interact input is pressed.
/// activate interact of objectToInteractWith if both return true.
/// </summary>
private void CheckForInteractionInput()
{
if (objectToInteractWith != null)
{
objectToInteractWith.Interact();
}
else
{
Debug.Log("No Interactable Detected");
}
}
}