Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice
  3. Dismiss Notice

Question Compare a random color generated to the color of a ball from live video

Discussion in 'Scripting' started by SavageH, May 17, 2024.

  1. SavageH

    SavageH

    Joined:
    Mar 21, 2024
    Posts:
    3
    Hi everyone,

    I am new to Unity and c# programming and I am having some difficulties to write a code that allows me to compare a random color generated to a color of a foam ball in a live video from my webcam. If the person picks the foam ball with the same color as the random assigned and show it in the video, appears a text saying “correct” and new random color is generated, if not it waits until the colors match.

    Ideally it would compare the live ball color and match it to the one with less difference among the random pool of colors and then check if this color is the one it was supposed to be picked or not. I already have a script to show the live camera placed in a GameObject and it works fine.

    I’ve putted some texts showing on screen to help the person using to keep track of what color they are supposed to pick and defined a limit of 5 balls, for example. Also, the colors I placed on the script are the ones I have foam balls available.

    I’ve written a code with what I little understand and could find online, but it is not working, nevertheless I will place it here so that anyone can have a better idea of what I mean, even though it most likely to be completely incorrect.

    The script:
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.SceneManagement;
    5. using UnityEngine.UI;
    6. using TMPro;
    7.  
    8. public class ColorGenerator : MonoBehaviour
    9. {
    10.     // Array of colors
    11.     private string[] colors = { "red", "blue", "green", "yellow", "purple", "pink", "brown", "orange" };
    12.  
    13.     // Center text
    14.     public TextMeshProUGUI centerText;
    15.  
    16.     // Right text
    17.     public TextMeshProUGUI rightText;
    18.  
    19.     public TextMeshProUGUI leftText;
    20.  
    21.     // Color index
    22.     private int colorIndex = 0;
    23.  
    24.     // The random color
    25.     private string randomColor;
    26.  
    27.     // The Live Camera GameObject
    28.     public GameObject liveCamera;
    29.  
    30.     private void GenerateColor()
    31.     {
    32.         // Generate a random color index, excluding black and white
    33.         int randomIndex = Random.Range(0, colors.Length);
    34.  
    35.         // Get the random color
    36.         randomColor = colors[randomIndex];
    37.  
    38.         // Display the center text for 3 seconds
    39.         centerText.text = $"Remove the {randomColor} ball";
    40.         StartCoroutine(ShowCenterTextFor3Seconds());
    41.     }
    42.  
    43.     private IEnumerator ShowCenterTextFor3Seconds()
    44.     {
    45.         yield return new WaitForSeconds(3f);
    46.         centerText.enabled = false;
    47.  
    48.         // Display the right text with the color and index
    49.         rightText.text = $"Remove the {randomColor} ball ({+colorIndex}/5)";
    50.         rightText.enabled = true;
    51.  
    52.         // Compare the color of the ball in the live feed with the generated color
    53.         Color detectedColor = DetectColor(liveCamera);
    54.         if (IsColorMatch(detectedColor, randomColor))
    55.         {
    56.             // Display the "correct" text for 1 second
    57.             centerText.text = "Correct";
    58.             centerText.color = Color.green;
    59.             centerText.enabled = true;
    60.             yield return new WaitForSeconds(1f);
    61.             centerText.enabled = false;
    62.  
    63.             // Check if all colors have been correctly removed
    64.             if (colorIndex == 5)
    65.             {
    66.                 // Load scene 5
    67.                 SceneManager.LoadScene(2);
    68.             }
    69.  
    70.             // Generate a new color and increase the color index
    71.             GenerateColor();
    72.             colorIndex++;
    73.         }
    74.         else
    75.         {
    76.             // Display the "incorrect" text for 1 second
    77.             centerText.text = "Incorrect";
    78.             centerText.color = Color.red;
    79.             centerText.enabled = true;
    80.             yield return new WaitForSeconds(1f);
    81.             centerText.enabled = false;
    82.         }
    83.     }
    84.  
    85.     private Color DetectColor(GameObject camera)
    86.     {
    87.         // Get the camera's texture
    88.         WebCamTexture texture = camera.GetComponent<WebCamTexture>();
    89.  
    90.         // Get the color of the center pixel
    91.         int width = texture.width;
    92.         int height = texture.height;
    93.         int centerX = width / 2;
    94.         int centerY = height / 2;
    95.         Color color = texture.GetPixel(centerX, centerY);
    96.  
    97.         // Ignore white pixels
    98.         if (color.r > 0.9f && color.g > 0.9f && color.b > 0.9f)
    99.         {
    100.             return Color.clear;
    101.         }
    102.  
    103.         return color;
    104.     }
    105.  
    106.     private bool IsColorMatch(Color detectedColor, string generatedColor)
    107.     {
    108.         // Convert the generated color to a Color object
    109.         Color generatedColorObject = new Color();
    110.         // Compare the detected color with the generated color
    111.         switch (generatedColor)
    112.         {
    113.             case "red":
    114.                 return CompareColor(detectedColor, Color.red);
    115.             case "green":
    116.                 return CompareColor(detectedColor, Color.green);
    117.             case "orange":
    118.                 return CompareColor(detectedColor, new Color(1f, 0.6f, 0f)); // orange
    119.             case "yellow":
    120.                 return CompareColor(detectedColor, Color.yellow);
    121.             case "blue":
    122.                 return CompareColor(detectedColor, Color.blue); // blue
    123.             case "purple":
    124.                 return CompareColor(detectedColor, new Color(0.5f, 0f, 0.5f)); // purple
    125.             case "pink":
    126.                 return CompareColor(detectedColor, new Color(1f, 0f, 0.5f)); // pink
    127.             case "brown":
    128.                 return CompareColor(detectedColor, new Color(0.6f, 0.4f, 0.2f)); // brown
    129.             default:
    130.                 return false;
    131.         }
    132.     }
    133.  
    134.     private bool CompareColor(Color detectedColor, Color generatedColor)
    135.     {
    136.         // Define the threshold for each RGB channel
    137.         float threshold = 0.1f;
    138.  
    139.         // Compare the detected color with the generated color
    140.         return Mathf.Abs(detectedColor.r - generatedColor.r) <= threshold
    141.             && Mathf.Abs(detectedColor.g - generatedColor.g) <= threshold
    142.             && Mathf.Abs(detectedColor.b - generatedColor.b) <= threshold;
    143.         leftText.text = $"{ detectedColor.ToString()}";
    144.     }
    145. }


    If anyone can help me fix it or show a better one I will be very grateful!

    Thanks to everyone in advance!
     
  2. dstears

    dstears

    Joined:
    Sep 6, 2021
    Posts:
    217
    When you say "it is not working", what part isn't working? What behavior are you getting that is incorrect?
     
  3. SavageH

    SavageH

    Joined:
    Mar 21, 2024
    Posts:
    3
    When I press play, just shows the video and nothing else. Not even the text indicating the color.
     
  4. dstears

    dstears

    Joined:
    Sep 6, 2021
    Posts:
    217
    What is supposed to call GenerateColor? This is private, so it can't be done from outside this script and you don't have any Start(), Update(), or Awake() functions here to call it at the beginning of time.

    It is often very helpful to put Debug.Log prints in various places in your code so that you know if the code is reaching a certain function or branch of execution. It is also very helpful to print out the value of variables to see if you are getting the values you expect.
     
  5. SavageH

    SavageH

    Joined:
    Mar 21, 2024
    Posts:
    3
    Ok! Thank you very much! I will try this out