Tanoda
ObjectControl.cs
Go to the documentation of this file.
1using System;
2using System.Collections.Generic;
3using UnityEngine;
4using Random = UnityEngine.Random;
5
6namespace Waypoint
7{
8 public class ObjectControl : MonoBehaviour
9 {
10 #region FIELDS
11
12 [SerializeField] private WaypointCircuit _waypointCircuit;
13
14 [SerializeField] private ObjectMove _objectMove;
15
16 [SerializeField] private bool _isDrive = true;
17
18 [SerializeField] private bool _isWait;
19
20 [SerializeField] private bool _isRepeat = true;
21
22 private List<Vector3> _points;
23 private Vector3 _currentPoint;
24 private int _pointIndex;
25 private float _wait;
26
27 public event Action OnEndPath;
28 public event Action OnRepeatPath;
29
30 #endregion
31
32 #region UNITY_METHODS
33
34 private void Awake()
35 {
36 _wait = Random.Range(1.0f, 5.0f);
37 }
38
39 private void Start()
40 {
41 _points = _waypointCircuit._curvePoints;
42 _currentPoint = _points[0];
43 }
44
45 private void Update()
46 {
47 if (!_isDrive) return;
48 if (_isWait)
49 WaitStart();
50 else
51 _objectMove.Move(_currentPoint);
52 }
53
54 private void OnEnable()
55 {
56 _objectMove.OnEndOfRoad += GetNextPoint;
57 }
58
59 private void OnDisable()
60 {
61 _objectMove.OnEndOfRoad -= GetNextPoint;
62 }
63
64 #endregion
65
66 #region PRIVATE_METHODS
67
68 private void WaitStart()
69 {
70 _wait -= Time.deltaTime;
71
72 if (_wait < 0) _isWait = false;
73 }
74
75 private void GetNextPoint()
76 {
77 if (_waypointCircuit.Circuit)
78 {
79 if (_pointIndex >= _points.Count - 1)
80 {
81 if (_pointIndex == _points.Count - 1)
82 {
83 EndPath();
84 }
85 else
86 {
87 _pointIndex++;
88 _currentPoint = _points[0];
89 }
90 }
91 else
92 {
93 _pointIndex++;
94 _currentPoint = _points[_pointIndex];
95 }
96 }
97 else
98 {
99 if (_pointIndex >= _points.Count - 1)
100 {
101 EndPath();
102 }
103 else
104 {
105 _pointIndex++;
106 _currentPoint = _points[_pointIndex];
107 }
108 }
109 }
110
111 private void EndPath()
112 {
113 if (_isRepeat)
114 {
115 _pointIndex = 0;
116
117 OnRepeatPath?.Invoke();
118 }
119 else
120 {
121 _isDrive = false;
122
123 OnEndPath?.Invoke();
124 }
125 }
126
127 #endregion
128 }
129}
UnityEngine.Random Random
void Move(Vector3 currentPoint)
Definition: ObjectMove.cs:91
List< Vector3 > _curvePoints