Commit e94cf53a authored by Mahmoud Aglan's avatar Mahmoud Aglan

Fix challenge crash

parent ac3d4138
......@@ -37,6 +37,10 @@ public class ChallengeManager : MonoBehaviour
private float _lastGameTimeLeft = 0f;
public float LastGameTimeLeft => _lastGameTimeLeft;
// ✅ NEW: prevent double-start
private bool _challengeRunning = false;
public bool IsChallengeRunning => _challengeRunning;
// ─── Singleton ────────────────────────────────────────────────────────
private void Awake()
{
......@@ -71,6 +75,9 @@ public class ChallengeManager : MonoBehaviour
// ─── Challenge flow ───────────────────────────────────────────────────
public async UniTask StartChallenge()
{
if (_challengeRunning) return; // prevent double-start
_challengeRunning = true;
startTime = DateTime.UtcNow;
currentGameIndex = 0;
timeSaved = 0;
......@@ -83,20 +90,16 @@ public class ChallengeManager : MonoBehaviour
private void OnGameCompleted(bool hasWon, float timeLeft, float pointsEarned)
{
print("Game completed");
if (currentGame != null)
currentGame.OnGameCompleted -= OnGameCompleted;
if (!hasWon)
{
LostChallenge();
LostChallenge().Forget();
return;
}
// ✅ NEW: store timeLeft so the next game can use it as a bonus
_lastGameTimeLeft = timeLeft;
// Add time left to total saved time
timeSaved += Mathf.RoundToInt(timeLeft);
currentGameIndex++;
......@@ -139,16 +142,19 @@ public class ChallengeManager : MonoBehaviour
private async UniTask LostChallenge()
{
Debug.Log("Challenge failed.");
challengeCanvas.ShowChallengeResult(
false, 0, penaltiesPerGame[currentGameIndex]);
_challengeRunning = false;
int maxPenalty = penaltiesPerGame[currentGameIndex];
int currentPoints = UserService.Instance.CurrentUser?.Points ?? 0;
int actualPenalty = Mathf.Min(maxPenalty, currentPoints);
challengeCanvas.ShowChallengeResult(false, 0, actualPenalty);
await ChallengeService.Instance.AddChallenge(
false, 0, -penaltiesPerGame[currentGameIndex], startTime, DateTime.UtcNow);
false, 0, -actualPenalty, startTime, DateTime.UtcNow);
}
private async UniTask WonChallenge(int timeSaved, int pointsEarned)
{
Debug.Log("Challenge completed! Total time saved: " + timeSaved);
_challengeRunning = false;
challengeCanvas.ShowChallengeResult(true, timeSaved, pointsEarned);
await ChallengeService.Instance.AddChallenge(
true, timeSaved, pointsEarned, startTime, DateTime.UtcNow);
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment