Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions Assets/Scenes/EmptyRoom_2.unity
Original file line number Diff line number Diff line change
Expand Up @@ -690,6 +690,10 @@ PrefabInstance:
propertyPath: m_Layer
value: 6
objectReference: {fileID: 0}
- target: {fileID: 8096972002182311090, guid: 35bed5d2a54129845bcff6b3abaa746b, type: 3}
propertyPath: trapPrefabs.Array.data[1]
value:
objectReference: {fileID: 411694592779797494, guid: d7c2a5ac1f23afe428f872343ed56d71, type: 3}
- target: {fileID: 8327367539400217474, guid: 35bed5d2a54129845bcff6b3abaa746b, type: 3}
propertyPath: m_Layer
value: 6
Expand Down Expand Up @@ -877,6 +881,10 @@ PrefabInstance:
propertyPath: m_LocalEulerAnglesHint.z
value: 0
objectReference: {fileID: 0}
- target: {fileID: 3966805182529176642, guid: b95a2840877394746b9c857ec618031d, type: 3}
propertyPath: m_IsActive
value: 1
objectReference: {fileID: 0}
- target: {fileID: 4190906850344886629, guid: b95a2840877394746b9c857ec618031d, type: 3}
propertyPath: m_Name
value: Main Camera
Expand Down
46 changes: 45 additions & 1 deletion Assets/Scripts/Player/PlayerController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
using UnityEngine;
using SocketIOClient;
using CandyCoded.env;
using System.IO;
using System.Collections.Generic;

public class PlayerMovement : MonoBehaviour
{
Expand All @@ -28,6 +30,32 @@ public class PlayerMovement : MonoBehaviour
public Vector2 maxCameraPosition;
private string socketUrl;

private void LoadEnvVariables()
{
string envFilePath = Path.Combine(Application.dataPath, ".env");

if (File.Exists(envFilePath))
{
foreach (var line in File.ReadAllLines(envFilePath))
{
if (!string.IsNullOrWhiteSpace(line) && !line.StartsWith("#"))
{
var keyValue = line.Split('=');
if (keyValue.Length == 2)
{
var key = keyValue[0].Trim();
var value = keyValue[1].Trim();
Environment.SetEnvironmentVariable(key, value);
}
}
}
}
else
{
Debug.LogError(".env file not found at " + envFilePath);
}
}
Comment on lines +33 to +57
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Attention à la gestion des chemins de fichiers sur Windows

La méthode LoadEnvVariables présente plusieurs points à améliorer :

  1. L'utilisation de Path.Combine est bonne pour la compatibilité Windows, mais Application.dataPath n'est peut-être pas le meilleur choix pour stocker le fichier .env.
  2. Il manque une validation du contenu des variables d'environnement.
  3. La méthode fait double emploi avec CandyCoded.env déjà importé.

Suggestions d'amélioration :

 private void LoadEnvVariables()
 {
-    string envFilePath = Path.Combine(Application.dataPath, ".env");
+    string envFilePath = Path.Combine(Application.persistentDataPath, ".env");

     if (File.Exists(envFilePath))
     {
         foreach (var line in File.ReadAllLines(envFilePath))
         {
             if (!string.IsNullOrWhiteSpace(line) && !line.StartsWith("#"))
             {
                 var keyValue = line.Split('=');
                 if (keyValue.Length == 2)
                 {
                     var key = keyValue[0].Trim();
                     var value = keyValue[1].Trim();
+                    if (string.IsNullOrEmpty(key) || string.IsNullOrEmpty(value))
+                    {
+                        Debug.LogWarning($"Variable d'environnement invalide : {line}");
+                        continue;
+                    }
                     Environment.SetEnvironmentVariable(key, value);
                 }
             }
         }
     }
     else
     {
-        Debug.LogError(".env file not found at " + envFilePath);
+        Debug.LogError($"Fichier .env non trouvé : {envFilePath}");
     }
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
private void LoadEnvVariables()
{
string envFilePath = Path.Combine(Application.dataPath, ".env");
if (File.Exists(envFilePath))
{
foreach (var line in File.ReadAllLines(envFilePath))
{
if (!string.IsNullOrWhiteSpace(line) && !line.StartsWith("#"))
{
var keyValue = line.Split('=');
if (keyValue.Length == 2)
{
var key = keyValue[0].Trim();
var value = keyValue[1].Trim();
Environment.SetEnvironmentVariable(key, value);
}
}
}
}
else
{
Debug.LogError(".env file not found at " + envFilePath);
}
}
private void LoadEnvVariables()
{
string envFilePath = Path.Combine(Application.persistentDataPath, ".env");
if (File.Exists(envFilePath))
{
foreach (var line in File.ReadAllLines(envFilePath))
{
if (!string.IsNullOrWhiteSpace(line) && !line.StartsWith("#"))
{
var keyValue = line.Split('=');
if (keyValue.Length == 2)
{
var key = keyValue[0].Trim();
var value = keyValue[1].Trim();
if (string.IsNullOrEmpty(key) || string.IsNullOrEmpty(value))
{
Debug.LogWarning($"Variable d'environnement invalide : {line}");
continue;
}
Environment.SetEnvironmentVariable(key, value);
}
}
}
}
else
{
Debug.LogError($"Fichier .env non trouvé : {envFilePath}");
}
}


async void Start()
{
player = GetComponent<Player>();
Expand All @@ -53,6 +81,21 @@ async void Start()
cameraWidth = cameraHeight * mainCamera.aspect;
}

try
{
LoadEnvVariables();
var socketUrl = Environment.GetEnvironmentVariable("SOCKET_URL");
var uri = new Uri(socketUrl);
clientSocket = SocketManager.Instance.ClientSocket;
if (clientSocket == null)
{
Debug.LogError("SocketIO client is null! Check SocketManager initialization.");
}
}
catch (Exception e)
{
Debug.LogError("Socket connection error: " + e.Message);
}
Comment on lines +84 to +98
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Code dupliqué dans la méthode Start

Il y a une duplication du bloc try-catch pour la configuration du socket. De plus, vous mélangez deux approches différentes pour charger les variables d'environnement.

Suggestion de refactorisation :

 try
 {
     LoadEnvVariables();
-    var socketUrl = Environment.GetEnvironmentVariable("SOCKET_URL");
-    var uri = new Uri(socketUrl);
-    clientSocket = SocketManager.Instance.ClientSocket;
-    if (clientSocket == null)
-    {
-        Debug.LogError("SocketIO client is null! Check SocketManager initialization.");
-    }
- }
- catch (Exception e)
- {
-    Debug.LogError("Socket connection error: " + e.Message);
- }
- try
- {
     env.TryParseEnvironmentVariable("SOCKET_URL", out string socketUrl);
     var uri = new Uri(socketUrl);
     clientSocket = SocketManager.Instance.ClientSocket;

     if (clientSocket == null)
     {
-        Debug.LogError("SocketIO client is null! Check SocketManager initialization.");
+        Debug.LogError("Le client SocketIO est null ! Vérifiez l'initialisation du SocketManager.");
     }
 }
 catch (Exception e)
 {
-    Debug.LogError("Socket connection error: " + e.Message);
+    Debug.LogError($"Erreur de connexion socket : {e.Message}");
 }

Committable suggestion was skipped due to low confidence.

try
{
env.TryParseEnvironmentVariable("SOCKET_URL", out string socketUrl);
Expand Down Expand Up @@ -165,10 +208,11 @@ async void SendData(string channel, string data)
{
await clientSocket.EmitAsync(channel, data);
}

}
catch (Exception e)
{
Debug.LogError("Socket send error: " + e.Message);
UnityEngine.Debug.LogError("Socket send error: " + e.Message);
}
}

Expand Down
46 changes: 46 additions & 0 deletions Assets/Scripts/SocketManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
using UnityEngine;
using SocketIOClient;
using CandyCoded.env;
using System.IO;
using System.Collections.Generic;

public class SocketManager : MonoBehaviour
{
Expand All @@ -25,8 +27,52 @@ private void Awake()
}
}

private void LoadEnvVariables()
{
string envFilePath = Path.Combine(Application.dataPath, ".env");

if (File.Exists(envFilePath))
{
foreach (var line in File.ReadAllLines(envFilePath))
{
if (!string.IsNullOrWhiteSpace(line) && !line.StartsWith("#"))
{
var keyValue = line.Split('=');
if (keyValue.Length == 2)
{
var key = keyValue[0].Trim();
var value = keyValue[1].Trim();
Environment.SetEnvironmentVariable(key, value);
}
}
}
}
else
{
Debug.LogError(".env file not found at " + envFilePath);
}
}
Comment on lines +30 to +54
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Améliorer la gestion des variables d'environnement

La méthode LoadEnvVariables présente plusieurs points à améliorer :

  1. Il manque une validation du contenu des variables d'environnement
  2. Les erreurs ne sont pas gérées lors de la lecture du fichier
  3. Le chemin du fichier .env pourrait être problématique sur certaines plateformes

Voici une version améliorée :

 private void LoadEnvVariables()
 {
-    string envFilePath = Path.Combine(Application.dataPath, ".env");
+    string envFilePath = Path.Combine(Application.persistentDataPath, ".env");

     if (File.Exists(envFilePath))
     {
-        foreach (var line in File.ReadAllLines(envFilePath))
+        try
         {
-            if (!string.IsNullOrWhiteSpace(line) && !line.StartsWith("#"))
+            foreach (var line in File.ReadAllLines(envFilePath))
             {
-                var keyValue = line.Split('=');
-                if (keyValue.Length == 2)
+                if (!string.IsNullOrWhiteSpace(line) && !line.StartsWith("#"))
                 {
-                    var key = keyValue[0].Trim();
-                    var value = keyValue[1].Trim();
-                    Environment.SetEnvironmentVariable(key, value);
+                    var keyValue = line.Split(new[] { '=' }, 2);
+                    if (keyValue.Length == 2)
+                    {
+                        var key = keyValue[0].Trim();
+                        var value = keyValue[1].Trim();
+                        if (!string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(value))
+                        {
+                            Environment.SetEnvironmentVariable(key, value);
+                        }
+                    }
                 }
             }
         }
+        catch (Exception e)
+        {
+            Debug.LogError($"Erreur lors de la lecture du fichier .env : {e.Message}");
+        }
     }
     else
     {
-        Debug.LogError(".env file not found at " + envFilePath);
+        Debug.LogError($"Fichier .env non trouvé : {envFilePath}");
     }
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
private void LoadEnvVariables()
{
string envFilePath = Path.Combine(Application.dataPath, ".env");
if (File.Exists(envFilePath))
{
foreach (var line in File.ReadAllLines(envFilePath))
{
if (!string.IsNullOrWhiteSpace(line) && !line.StartsWith("#"))
{
var keyValue = line.Split('=');
if (keyValue.Length == 2)
{
var key = keyValue[0].Trim();
var value = keyValue[1].Trim();
Environment.SetEnvironmentVariable(key, value);
}
}
}
}
else
{
Debug.LogError(".env file not found at " + envFilePath);
}
}
private void LoadEnvVariables()
{
string envFilePath = Path.Combine(Application.persistentDataPath, ".env");
if (File.Exists(envFilePath))
{
try
{
foreach (var line in File.ReadAllLines(envFilePath))
{
if (!string.IsNullOrWhiteSpace(line) && !line.StartsWith("#"))
{
var keyValue = line.Split(new[] { '=' }, 2);
if (keyValue.Length == 2)
{
var key = keyValue[0].Trim();
var value = keyValue[1].Trim();
if (!string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(value))
{
Environment.SetEnvironmentVariable(key, value);
}
}
}
}
}
catch (Exception e)
{
Debug.LogError($"Erreur lors de la lecture du fichier .env : {e.Message}");
}
}
else
{
Debug.LogError($"Fichier .env non trouvé : {envFilePath}");
}
}


private async Task SetupSocket()
{

LoadEnvVariables();

try
{
var socketUrl = Environment.GetEnvironmentVariable("SOCKET_URL");
var uri = new Uri(socketUrl);
ClientSocket = new SocketIOUnity(uri);

// Connect to the server
await ClientSocket.ConnectAsync();
Debug.Log("Connected to backend via SocketManager.");
}
catch (Exception e)
{
Debug.LogError("Socket connection error: " + e.Message);
}
Comment on lines +58 to +74
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Code dupliqué dans SetupSocket

Il y a une duplication du bloc try-catch pour la connexion socket. De plus, deux approches différentes sont utilisées pour récupérer l'URL du socket.

Voici la correction proposée :

 private async Task SetupSocket()
 {
     LoadEnvVariables(); 

     try
     {
-        var socketUrl = Environment.GetEnvironmentVariable("SOCKET_URL");
-        var uri = new Uri(socketUrl);
-        ClientSocket = new SocketIOUnity(uri);
-
-        // Connect to the server
-        await ClientSocket.ConnectAsync();
-        Debug.Log("Connected to backend via SocketManager.");
-    }
-    catch (Exception e)
-    {
-        Debug.LogError("Socket connection error: " + e.Message);
-    }
-
-    try
-    {
-        env.TryParseEnvironmentVariable("SOCKET_URL", out string socketUrl);
+        if (!env.TryParseEnvironmentVariable("SOCKET_URL", out string socketUrl))
+        {
+            throw new Exception("Variable d'environnement SOCKET_URL non définie");
+        }
         var uri = new Uri(socketUrl);
         ClientSocket = new SocketIOUnity(uri);

         // Connect to the server
         await ClientSocket.ConnectAsync();
-        Debug.Log("Connected to backend via SocketManager.");
+        Debug.Log("Connecté au backend via SocketManager.");
     }
     catch (Exception e)
     {
-        Debug.LogError("Socket connection error: " + e.Message);
+        Debug.LogError($"Erreur de connexion socket : {e.Message}");
     }
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
LoadEnvVariables();
try
{
var socketUrl = Environment.GetEnvironmentVariable("SOCKET_URL");
var uri = new Uri(socketUrl);
ClientSocket = new SocketIOUnity(uri);
// Connect to the server
await ClientSocket.ConnectAsync();
Debug.Log("Connected to backend via SocketManager.");
}
catch (Exception e)
{
Debug.LogError("Socket connection error: " + e.Message);
}
LoadEnvVariables();
try
{
if (!env.TryParseEnvironmentVariable("SOCKET_URL", out string socketUrl))
{
throw new Exception("Variable d'environnement SOCKET_URL non définie");
}
var uri = new Uri(socketUrl);
ClientSocket = new SocketIOUnity(uri);
// Connect to the server
await ClientSocket.ConnectAsync();
Debug.Log("Connecté au backend via SocketManager.");
}
catch (Exception e)
{
Debug.LogError($"Erreur de connexion socket : {e.Message}");
}


try
{
env.TryParseEnvironmentVariable("SOCKET_URL", out string socketUrl);
Expand Down
7 changes: 0 additions & 7 deletions Assets/Scripts/Trap/TrapManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -114,13 +114,6 @@ private void SpawnTrapAtPosition(int x, int y, string trapType)
}
}

void OnApplicationQuit()
{
if (clientSocket != null)
{
clientSocket.Dispose(); // Properly close the connection
}
}

private class TrapPlacement
{
Expand Down
10 changes: 4 additions & 6 deletions Assets/Scripts/UI/PlayerHealth.cs
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,6 @@ public void Heal(int amount)
if (currentHealth > maxHealth)
{
currentHealth = maxHealth;
}
UpdateHealthBar();
}

Expand All @@ -60,15 +59,14 @@ private async void SocketEmitter()

void Die()
{
SocketEmitter();
if (deadCanvas != null)

if (deadCanvas != null && !deadCanvas.activeSelf)
{
SocketEmitter();
deadCanvas.SetActive(true);
}
GetComponent<PlayerMovement>().enabled = false;
}


void UpdateHealthBar()
{

Expand All @@ -82,7 +80,7 @@ void UpdateHealthBar()
for (int i = 0; i < currentHealth; i++)
{
GameObject newHeart = Instantiate(heartPrefab, healthBar);
hearts.Add(newHeart); // Ajouter le c�ur � la liste pour le traquer
hearts.Add(newHeart);
}
}

Expand Down