Skip to content

Commit 4a38ad3

Browse files
committed
Updated Example with Coroutines
1 parent b0f4ecd commit 4a38ad3

File tree

1 file changed

+24
-11
lines changed

1 file changed

+24
-11
lines changed

Assets/UXF/Examples/Advanced/Scripts/StartBlockController.cs

Lines changed: 24 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -22,22 +22,38 @@ public class StartBlockController : MonoBehaviour
2222
public Session session;
2323

2424
StartBlockState state = StartBlockState.Waiting;
25-
2625
SpriteRenderer spriteRenderer;
26+
Coroutine runningSequence;
27+
2728

2829
void Awake()
2930
{
3031
spriteRenderer = GetComponent<SpriteRenderer>();
3132
SetState(StartBlockState.Waiting);
3233
}
3334

34-
public void SetState(StartBlockState newState)
35+
36+
IEnumerator RunSequence()
37+
{
38+
GetReady();
39+
40+
// Take the delay time (seconds) for the next trial, wait for that time
41+
// If we move from the start block too early, StopCoroutine(runningSequence); will halt the execution of this coroutine
42+
// System.Convert: Safely convert to single (float)
43+
float delayTime = System.Convert.ToSingle(session.nextTrial.settings["delay_time"]);
44+
yield return new WaitForSeconds(delayTime);
45+
46+
Go();
47+
}
48+
49+
void SetState(StartBlockState newState)
3550
{
36-
StartBlockState oldState = state;
3751
state = newState;
3852

53+
// modify colour based on state
3954
switch (state)
4055
{
56+
// could be dictionary
4157
case StartBlockState.Waiting:
4258
spriteRenderer.color = mainColor;
4359
break;
@@ -59,13 +75,7 @@ public void ResetToNormal()
5975
void GetReady()
6076
{
6177
Debug.Log("Get ready...");
62-
6378
SetState(StartBlockState.GetReady);
64-
65-
// Take the delay time (seconds) for the next trial, and invoke the "Go" method after that time
66-
// safely convert to single (float)
67-
float delayTime = System.Convert.ToSingle(session.nextTrial.settings["delay_time"]);
68-
Invoke("Go", delayTime);
6979
}
7080

7181
void Go()
@@ -82,7 +92,8 @@ void OnMouseEnter()
8292
switch (state)
8393
{
8494
case StartBlockState.Waiting:
85-
GetReady();
95+
// begin the sequence
96+
runningSequence = StartCoroutine(RunSequence());
8697
break;
8798
}
8899
}
@@ -92,7 +103,9 @@ void OnMouseExit()
92103
switch (state)
93104
{
94105
case StartBlockState.GetReady:
95-
CancelInvoke("Go");
106+
// stop the sequence
107+
Debug.Log("Moved too early!");
108+
StopCoroutine(runningSequence);
96109
ResetToNormal();
97110
break;
98111
case StartBlockState.Go:

0 commit comments

Comments
 (0)