EloiStree / HelloSharpForUnity3D

Here we are going to check all the basic need to work in Unity3D with C#
0 stars 0 forks source link

Topic: OpenClass Room à Unity3D: #447

Open EloiStree opened 1 week ago

EloiStree commented 1 week ago

image image

Code Monkey guide: https://www.youtube.com/watch?v=pReR6Z9rK-o Site du Zero guide: https://synchronicales.eu/sdz/sdz/apprenez-a-developper-en-c.html PDF: SiteDuZeroC#.pdf W3C: https://www.w3schools.com/cs/index.php

EloiStree commented 1 week ago

Source: https://openclassrooms.com/en/courses/5670356-learn-programming-with-c/6080861-unravel-the-variable-making-declarations-and-changing-values

Variables

Nom Type Valeur
life int 40, 20, life + 4, ...
rest int life % 9
isPair bool rest % 2 == 0
powerPercent float 9000
text string "Bonjour"
entier int 42
grandNombre double 42.14564645546
nombre float 3.14
theAnswer const int 42

Opérations

Exemple de code

// Déclaration et initialisation des variables
int life = 40;
life = 20;
life = life + 4;  // Addition
life += 5;        // Incrémentation de 5
life++;           // Incrémentation de 1
life--;           // Décrémentation de 1

// Opérations arithmétiques
life = life / 10; // Division
life = life * 100; // Multiplication
int rest = life % 9; // Reste de la division par 9
bool isPair = rest % 2 == 0; // Vérification si 'rest' est pair

float powerPercent = 1f;
powerPercent *= 9000f; // Multiplication par 9000

// Commentaire sur une ligne

/* 
Commentaire
sur plusieurs lignes
 */

// Exemples de déclaration de constantes et de chaînes de caractères
string text = "Bonjour ";
int entier = 42;
double grandNombre = 42.14564645546;
float nombre = 3.14f;

const int theAnswer = 42; // Constante

char [] bonjourAsArray = text.ToArray();
bonjourAsArray[3] = 'g';
text  = bonjourAsArray.ToString();
EloiStree commented 1 week ago

https://openclassrooms.com/en/courses/5670356-learn-programming-with-c/6080871-understand-data-types-to-store-your-values

Type de Variable

// Déclaration de variables
bool unBoolean = true; // Initialisation avec la valeur true ou false
int unInteger = 42;
float unNombre = 3.14159265f; // 8 chiffres significatifs pour un float
double unGrandNombre = 45.5454345465; // 16 chiffres significatifs pour un double
decimal tropGrandNombre = 12345678901234567890123456.789m; // 28 chiffres significatifs pour un decimal

// Perte de valeur lors de la conversion
int a = (int)3.14; // Conversion en int, perd la valeur 0.14
int b = (int)3.98; // Conversion en int, perd la valeur 0.98
float c = 45; // Pas de perte de valeur

// Erreur de compilation : 3.14 est un double, et nécessite un suffixe 'f' pour être un float
float d = 3.14f; // Ajout de 'f' pour spécifier le type float

// Manipulation de chaînes de caractères
string s1 = "Hello";
string s2 = "World";
string s3 = "!";

// Concaténation de chaînes
string s4 = s1 + " " + s2 + s3;
string s5 = string.Format("{0} {1}{2}", s1, s2, s3);
string s6 = string.Join(" ", s1, s2, s3);
string s7 = string.Join(" ", new string[] { s1, s2, s3 });
EloiStree commented 1 week ago

https://openclassrooms.com/en/courses/5670356-learn-programming-with-c/6080881-define-objects-and-their-attributes-with-classes

Class

// Définition de la classe
public class PlayerPositionXZ
{
    public int m_x;
    public int m_z;

    public PlayerPositionXZ(int x, int z)
    {
        m_x = x;
        m_z = z;
    }
}

// Création d'une instance de la classe (un objet)
PlayerPositionXZ position = new PlayerPositionXZ(0, 0);

position.m_x = 1;
position.m_z = 2;
EloiStree commented 1 week ago

https://openclassrooms.com/en/courses/5670356-learn-programming-with-c/6080891-manage-complexity-with-the-right-collection image

Array

Here it is formatted in Markdown with C# syntax highlighting:

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        // Array
        int[] tableau = new int[5];
        tableau[0] = 1;
        tableau[1] = 2;
        tableau[2] = 3;
        tableau[3] = 4;
        tableau[4] = 5;

        // Alternative initialization of the array
        tableau = new int[] { 1, 2, 3, 4, 5 };

        float[,] grid = new float[65, 65];
        grid[0, 0] = 3.14f;
        grid[64, 64] = 6.28f;

        // Note: strings are immutable
        string name = "Eloi";
        // Converting string to char array to make it mutable
        char[] nameAsArray = name.ToCharArray();
        nameAsArray[0] = 'É';
        name = new string(nameAsArray);

        // List example
        List<int> myList = new List<int>();
        myList.Add(7);
        myList.Add(5);
        myList.Insert(0, 5); // Inserts 5 at index 0
        myList.Insert(myList.Count - 1, 1); // Inserts 1 at the second-last position
        myList.RemoveAt(1); // Removes element at index 1

        // HashSet example
        ISet<string> ingredients = new HashSet<string>();
        ingredients.Add("salt"); // Adds "salt" to ingredients
        ingredients.Remove("salt"); // Removes "salt" from ingredients

        // Dictionary and custom class example
        Dictionary<string, Score> dico = new Dictionary<string, Score>();
        dico.Add("Player1", new Score());
        dico.Add("Player2", new Score());

        if (dico.ContainsKey("Player1"))
        {
            dico["Player1"].m_last = 0;
            dico["Player1"].m_best = 0;
        }

        // Retrieving player names
        List<string> playersName = dico.Keys.ToList();
        string players = string.Join(", ", playersName);
        int playerNumber = playersName.Count;

        Console.WriteLine(players);
        Console.WriteLine("Number of players: " + playerNumber);
    }
}

[System.Serializable]
public class Score
{
    public string m_name;
    public float m_last;
    public float m_best;
}
EloiStree commented 1 week ago

https://openclassrooms.com/en/courses/5670356-learn-programming-with-c/6080901-understand-variable-scoping-and-access-control

Portée d'une variable

// Fonction avec variable locale
public void UneFonction()
{
    int variableLocal = 0;
    // La variable locale 'variableLocal' meurt ici
}

// Fonction avec retour de valeur
public int UneFonction()
{
    int variableLocal = 0;
    return variableLocal;
    // La variable locale 'variableLocal' meurt ici
}

// Classe A avec un destructeur
public class A
{
    public float m_variableMembre = 0;

    ~A()
    {
        // Le destructeur est appelé lorsque l'objet est libéré de la mémoire
        // m_variableMembre meurt ici
    }
}

// Classe B avec destructeur et méthode OnDestroy pour Unity3D
public class B
{
    public float m_variableMembre = 0;

    void OnDestroy()
    {
        // Cette méthode est appelée pour les objets Unity avant leur destruction
        // m_variableMembre se prépare à mourir ici
    }

    ~B()
    {
        // Le destructeur est appelé lorsque l'objet est libéré de la mémoire
    }
}

// Fonction avec des variables locales et un paramètre 'out'
public void UneFonction(int d, out int g)
{
    int b = 0;
    {
        int a = 0;
        // 'a' meurt ici, à la fin de son bloc de code
    }

    if (b == 0)
    {
        int c = b;
        // 'c' meurt ici, à la fin du bloc 'if'
    }
    // 'b' meurt ici, à la fin de la fonction
    // 'd' meurt ici, à la fin de la fonction
    // 'g' meurt ici, à la fin de la fonction
}
EloiStree commented 1 week ago

Protection des variables

using UnityEngine;

// Classe avec une variable privée
public class A : MonoBehaviour
{
    private int uneVariable;
    // Personne ne peut modifier 'uneVariable' directement, sauf les méthodes de la classe
}

// Classe avec une variable protégée
public class B : MonoBehaviour
{
    protected int uneVariable;
    // Seules les méthodes de cette classe et de ses classes dérivées peuvent modifier 'uneVariable'
}

// Classe avec une variable protégée et accessible dans l'inspecteur Unity
public class C : MonoBehaviour
{
    [SerializeField]
    protected int uneVariable;
    /*
    'uneVariable' est accessible uniquement par :
    - Les méthodes de cette classe
    - Ses classes dérivées
    - Les designers dans l'inspecteur Unity
    */
}

// Classe avec une variable publique mais cachée dans l'inspecteur Unity
public class D : MonoBehaviour
{
    [HideInInspector]
    public int uneVariable;
    /*
    La variable est publique, mais seulement visible et modifiable par les développeurs via le code, 
    pas par les designers dans l'inspecteur Unity
    */
}

// Classe avec une variable publique non protégée
public class E : MonoBehaviour
{
    public int uneVariable;
    /*
    La variable est accessible et modifiable partout.
    Utilisez avec prudence et envisagez d'ajouter une protection si nécessaire.
    */
}

// Classe avec encapsulation dans le style Java (méthodes Get/Set)
public class F : MonoBehaviour
{
    [Range(0, 2501)]
    private int uneVariable;

    // Méthode pour définir la valeur
    public void SetValue(int newValue)
    {
        uneVariable = Mathf.Clamp(newValue, 0, 2501); // Limite la valeur entre 0 et 2501
    }

    // Méthode pour obtenir la valeur
    public int GetValue()
    {
        return uneVariable;
    }

    // Méthode pour obtenir la valeur avec un paramètre de sortie
    public void GetValue(out int valueInGameObject)
    {
        valueInGameObject = uneVariable;
    }
}

// Classe avec encapsulation dans le style C# (propriétés)
public class G : MonoBehaviour
{
    [Range(0, 2501)]
    private int uneVariable;

    // Propriété pour encapsuler 'uneVariable' en lecture et écriture
    public int UneVariable
    {
        get { return uneVariable; }
        set 
        { 
            uneVariable = Mathf.Clamp(value, 0, 2501); // Limite la valeur entre 0 et 2501
        }
    }
}
EloiStree commented 1 week ago

https://openclassrooms.com/en/courses/5670356-learn-programming-with-c/6080926-get-your-program-started-with-the-main-function

Fonction

Static et get

using System; // Required for the Random class
using UnityEngine; // Required for Unity specific classes

namespace Eloi {

    // Example of a static toolbox for Pi
    public class ToolboxPI {

        // Use double for better precision
        static readonly double m_PI = 3.1418;
        public static double PI { get { return m_PI; } }

        public static double GetPI() {
            return m_PI;
        }

        // Using out parameter to get Pi
        public static void GetPI(out double pi) {
            pi = m_PI;
        }
    }

    public class Joystick {
        public float m_leftRight;
        public float m_downUp;
    }

    // Example of a toolbox for random joystick input
    public class ToolboxRandomInput {

        // Method to return a new Joystick instance with random values
        public Joystick GetRandomInput() {
            return new Joystick() {
                m_leftRight = UnityEngine.Random.Range(-1f, 1f),
                m_downUp = UnityEngine.Random.Range(-1f, 1f)
            };
        }

        // Using out parameter to return random joystick input
        public void GetRandomInput(out Joystick newValue) {
            newValue = GetRandomInput();
        }

        // Using ref parameter to affect an existing Joystick instance
        public void GetRandomInput(ref Joystick valueToAffect) {
            valueToAffect.m_leftRight = UnityEngine.Random.Range(-1f, 1f);
            valueToAffect.m_downUp = UnityEngine.Random.Range(-1f, 1f);
        }

        // Method to directly affect a Joystick instance without ref
        public void GetRandomInput(Joystick valueToAffect) {
            valueToAffect.m_leftRight = UnityEngine.Random.Range(-1f, 1f);
            valueToAffect.m_downUp = UnityEngine.Random.Range(-1f, 1f);
        }

        // Using out parameters for both leftRight and downUp
        public void GetRandomInput(out float leftRight, out float downUp) {
            leftRight = UnityEngine.Random.Range(-1f, 1f);
            downUp = UnityEngine.Random.Range(-1f, 1f);
        }
    }
}
´´´

```csharp
public bool IsValueInRangeClamp(in int value, in int min, in int max) {
    // Checks if the value is within the specified range, clamping if necessary
    return value >= min && value <= max;
}

public bool IsValueClamped(in int value, in int min, in int max, out bool isOut, out int outOfRangeValue) {
    // Initialize out parameters
    isOut = false;
    outOfRangeValue = value;

    // Check if value is within range
    if (value < min) {
        isOut = true;
        outOfRangeValue = min;
        return false;
    }
    if (value > max) {
        isOut = true;
        outOfRangeValue = max;
        return false;
    }

    // Value is within range
    return true;
}
EloiStree commented 1 week ago

Hello World Visual Studio


using System;

namespace Hello
{
    /// <summary>
    /// This is an implementation of the traditional "Hello world!" message
    /// </summary>
    /// <remarks>Created by the OpenClassrooms Education Team</remarks>
    public class HelloWorld 
    {
        /// <summary>
        /// This is where the program starts
        /// </summary>
        public static void Main(string[] args) 
        {
            Console.WriteLine("Hello World!");
        }
    }
}
EloiStree commented 1 week ago

String

1. ToUpper()

Converts all characters in a string to uppercase.

string text = "hello world";
Debug.Log(text.ToUpper()); // Output: "HELLO WORLD"

2. ToLower()

Converts all characters in a string to lowercase.

string text = "HELLO WORLD";
Debug.Log(text.ToLower()); // Output: "hello world"

3. Replace()

Replaces all occurrences of a specified substring with another substring.

string text = "hello world";
Debug.Log(text.Replace("world", "Unity")); // Output: "hello Unity"

4. IndexOf() and LastIndexOf()

IndexOf() returns the index of the first occurrence of a substring, or -1 if not found. LastIndexOf() finds the last occurrence.

string text = "hello world";
Debug.Log(text.IndexOf("world")); // Output: 6
Debug.Log(text.LastIndexOf("o")); // Output: 7

5. Substring()

Extracts a substring from a string, given a starting index and optional length.

string text = "hello world";
Debug.Log(text.Substring(6));      // Output: "world"
Debug.Log(text.Substring(0, 5));   // Output: "hello"

6. Trim(), TrimStart(), and TrimEnd()

Removes whitespace (or specified characters) from both ends of a string (Trim()), only the beginning (TrimStart()), or only the end (TrimEnd()).

string text = "  hello world  ";
Debug.Log(text.Trim());      // Output: "hello world"
Debug.Log(text.TrimStart()); // Output: "hello world  "
Debug.Log(text.TrimEnd());   // Output: "  hello world"

7. Contains()

Checks if a string contains a specified substring.

string text = "hello world";
Debug.Log(text.Contains("world")); // Output: True

8. StartsWith() and EndsWith()

Checks if a string starts or ends with a specified substring.

string text = "hello world";
Debug.Log(text.StartsWith("hello")); // Output: True
Debug.Log(text.EndsWith("world"));   // Output: True

9. Split() and Join()

Split() divides a string into an array of substrings. Join() concatenates elements of an array into a single string with a separator.

string text = "hello world unity";
string[] words = text.Split(' '); // Splits by space
Debug.Log(words[1]);              // Output: "world"

string joined = string.Join("-", words);
Debug.Log(joined);                // Output: "hello-world-unity"

10. Remove()

Removes characters from a string starting at a specified index and, optionally, for a specified length.

string text = "hello world";
Debug.Log(text.Remove(5));      // Output: "hello"
Debug.Log(text.Remove(0, 6));   // Output: "world"

11. Insert()

Inserts a string at a specified index.

string text = "hello world";
Debug.Log(text.Insert(6, "Unity ")); // Output: "hello Unity world"

12. Length Property

Returns the number of characters in the string.

string text = "hello world";
Debug.Log(text.Length); // Output: 11

13. Format()

Formats strings by inserting values into placeholders.

string name = "Alice";
int score = 42;
Debug.Log(string.Format("Player {0} scored {1} points!", name, score));
// Output: "Player Alice scored 42 points!"

14. String Interpolation ($)

Inserts variables into strings directly using $.

string name = "Alice";
int score = 42;
Debug.Log($"Player {name} scored {score} points!"); // Output: "Player Alice scored 42 points!"

15. Compare(), Equals(), and ==

string text1 = "hello";
string text2 = "Hello";

Debug.Log(string.Compare(text1, text2)); // Output: -1 (because "hello" is less than "Hello")
Debug.Log(text1.Equals(text2));          // Output: False (case-sensitive)
Debug.Log(text1 == text2);               // Output: False (case-sensitive)

16. ToCharArray()

Converts a string to a character array.

string text = "hello";
char[] chars = text.ToCharArray();
Debug.Log(chars[1]); // Output: "e"

17. IsNullOrEmpty() and IsNullOrWhiteSpace()

Checks if a string is null or empty (""), or only whitespace.

string text = "  ";
Debug.Log(string.IsNullOrEmpty(text));    // Output: False
Debug.Log(string.IsNullOrWhiteSpace(text)); // Output: True
EloiStree commented 1 week ago

1. Abs()

Returns the absolute value of a number.

float value = -10.5f;
Debug.Log(Mathf.Abs(value)); // Output: 10.5

2. Min() and Max()

Finds the minimum or maximum of two (or more) values.

float a = 3.2f, b = 5.6f;
Debug.Log(Mathf.Min(a, b)); // Output: 3.2
Debug.Log(Mathf.Max(a, b)); // Output: 5.6

3. Clamp()

Clamps a value between a minimum and maximum value.

float value = 15f;
Debug.Log(Mathf.Clamp(value, 0f, 10f)); // Output: 10

4. Clamp01()

Clamps a value between 0 and 1, often useful for normalizing.

float value = 1.5f;
Debug.Log(Mathf.Clamp01(value)); // Output: 1

5. Lerp() and LerpUnclamped()

Linearly interpolates between two values based on a normalized t (from 0 to 1). LerpUnclamped() allows t values outside this range.

float start = 0f, end = 10f;
float t = 0.5f;
Debug.Log(Mathf.Lerp(start, end, t)); // Output: 5

6. MoveTowards()

Gradually changes a value towards a target value by a specified maxDelta.

float current = 5f, target = 10f, maxDelta = 2f;
Debug.Log(Mathf.MoveTowards(current, target, maxDelta)); // Output: 7

7. SmoothDamp()

Smoothly changes a value towards a target, with control over speed and smoothness (requires a ref velocity variable).

float current = 0f, target = 10f, smoothTime = 0.3f;
float velocity = 0f;
Debug.Log(Mathf.SmoothDamp(current, target, ref velocity, smoothTime));
// Output: gradually approaches 10 with smoothing

8. PingPong()

Creates an oscillating value between 0 and a specified length.

float time = Time.time;
Debug.Log(Mathf.PingPong(time, 3f)); // Output: oscillates between 0 and 3

9. Repeat()

Loops a value around a given length (useful for looping animations).

float time = 8f;
Debug.Log(Mathf.Repeat(time, 3f)); // Output: 2 (wraps back around after 3)

10. Sign()

Returns the sign of a number as -1, 1, or 0.

float value = -10f;
Debug.Log(Mathf.Sign(value)); // Output: -1

11. Round(), Floor(), and Ceil()

Rounds a number to the nearest integer (Round()), rounds down to the nearest integer (Floor()), or rounds up to the nearest integer (Ceil()).

float value = 7.6f;
Debug.Log(Mathf.Round(value)); // Output: 8
Debug.Log(Mathf.Floor(value)); // Output: 7
Debug.Log(Mathf.Ceil(value));  // Output: 8

12. Pow() and Sqrt()

Pow() raises a number to a specified power, while Sqrt() calculates the square root of a number.

float baseNum = 2f, exponent = 3f;
Debug.Log(Mathf.Pow(baseNum, exponent)); // Output: 8
Debug.Log(Mathf.Sqrt(16f));             // Output: 4

13. Exp() and Log()

Exp() calculates the power of e (Euler's number), while Log() finds the logarithm of a number (natural by default, but Log10() is also available).

float value = 1f;
Debug.Log(Mathf.Exp(value));  // Output: 2.718 (e^1)
Debug.Log(Mathf.Log(10f));    // Output: 2.302 (natural log)
Debug.Log(Mathf.Log10(100f)); // Output: 2 (base 10 log)

14. Deg2Rad and Rad2Deg

Converts degrees to radians and vice versa.

float angle = 90f;
float radians = angle * Mathf.Deg2Rad; // Convert to radians
Debug.Log(radians); // Output: 1.5708 (pi/2)

float degrees = radians * Mathf.Rad2Deg; // Convert back to degrees
Debug.Log(degrees); // Output: 90

15. Sin(), Cos(), and Tan()

Calculates trigonometric sine, cosine, and tangent, respectively, for an angle given in radians.

float angleInRadians = Mathf.PI / 4; // 45 degrees
Debug.Log(Mathf.Sin(angleInRadians)); // Output: 0.7071
Debug.Log(Mathf.Cos(angleInRadians)); // Output: 0.7071
Debug.Log(Mathf.Tan(angleInRadians)); // Output: 1

16. Asin(), Acos(), and Atan()

Calculates the inverse trigonometric functions to get the angle in radians.

float value = 0.5f;
Debug.Log(Mathf.Asin(value)); // Output: 0.5236 (30 degrees in radians)
Debug.Log(Mathf.Acos(value)); // Output: 1.0472 (60 degrees in radians)
Debug.Log(Mathf.Atan(value)); // Output: 0.4636 (26.57 degrees in radians)

17. Atan2()

Calculates the angle in radians from the origin (0,0) to a point (y, x), accounting for the signs of both coordinates.

float y = 1f, x = 1f;
Debug.Log(Mathf.Atan2(y, x)); // Output: 0.7854 (45 degrees in radians)

18. Infinity and NegativeInfinity

Represents positive and negative infinity, useful for initializing variables.

float maxValue = Mathf.NegativeInfinity;
float minValue = Mathf.Infinity;
Debug.Log(maxValue); // Output: -Infinity
Debug.Log(minValue); // Output: Infinity

19. Approximately()

Compares two floating-point numbers and checks if they are approximately equal, accounting for floating-point precision errors.

float a = 0.1f * 3f;
float b = 0.3f;
Debug.Log(Mathf.Approximately(a, b)); // Output: True (since 0.1*3 is close to 0.3)

20. PerlinNoise()

Generates a pseudo-random float between 0.0 and 1.0 based on Perlin noise, which is smooth and commonly used in terrain generation.

float x = 0.5f, y = 0.5f;
Debug.Log(Mathf.PerlinNoise(x, y)); // Output: a value between 0 and 1
EloiStree commented 1 week ago

Appeler un méthode


SayYo(8);
int a =10;
SayTo(in a);

public void SayYo(in int numberOfO = 5)
{
    for (int i = 0; i < numberOfO; i++)
    {
        Debug.Log("Yo");
    }
}

1. Logging a Message

void Start()
{
    PrintMessage("Hello, Unity!");
}

void PrintMessage(string message)
{
    Debug.Log(message);
}

2. Calculating Sum

void Start()
{
    int result = AddNumbers(3, 4);
    Debug.Log("Sum: " + result); // Output: "Sum: 7"
}

int AddNumbers(int a, int b)
{
    return a + b;
}

3. Moving an Object

void Update()
{
    MoveObject(Vector3.up);
}

void MoveObject(Vector3 direction)
{
    transform.position += direction * Time.deltaTime;
}

4. Checking for a Condition

void Start()
{
    bool isEven = IsEven(8);
    Debug.Log("Is the number even? " + isEven); // Output: "Is the number even? True"
}

bool IsEven(int number)
{
    return number % 2 == 0;
}

5. Changing Object Color

void Start()
{
    ChangeColor(Color.red);
}

void ChangeColor(Color color)
{
    GetComponent<Renderer>().material.color = color;
}

6. Playing a Sound Effect

public AudioSource audioSource;
public AudioClip soundClip;

void Start()
{
    PlaySound(soundClip);
}

void PlaySound(AudioClip clip)
{
    audioSource.PlayOneShot(clip);
}
EloiStree commented 1 week ago

Condition

int power = 9001; if (power > 9000) { Debug.Log("Power level is over 9000!"); }

EloiStree commented 1 week ago

ForceSide.cs

using UnityEngine;

public class ForceSide : MonoBehaviour
{
    // Choisissez entre "obscur", "lumineux" ou n'importe quoi d'autre pour tester !
    public string coteDeLaForce = "obscur";

    void Start()
    {
        if (coteDeLaForce == "obscur")
        {
            Debug.Log("Attention ! Ce Jedi est passé du côté obscur de la Force !");
            ActiverSabreLaser("rouge");
        }
        else if (coteDeLaForce == "lumineux")
        {
            Debug.Log("C'est un Jedi fidèle à la lumière !");
            ActiverSabreLaser("bleu");
        }
        else
        {
            Debug.Log("Hmm... La Force est incertaine avec ce Jedi.");
            ActiverSabreLaser("violet");
        }
    }

    // Méthode pour afficher le sabre laser selon la couleur
    void ActiverSabreLaser(string couleur)
    {
        Debug.Log("Activation du sabre laser " + couleur + " ⚔️");
        // Ici, vous pourriez activer des effets visuels dans Unity selon la couleur choisie !
    }
}

JediSithSwitch.cs

using UnityEngine;

public class JediSithSwitch : MonoBehaviour
{
    // Choisissez entre "Jedi", "Sith" ou "Neutre" pour tester !
    public string typeDeForce = "Sith";

    void Start()
    {
        switch (typeDeForce)
        {
            case "Sith":
                Debug.Log("Un Sith est puissant dans le côté obscur de la Force !");
                ActiverSabreLaser("rouge");
                break;

            case "Jedi":
                Debug.Log("Un Jedi défend la paix et la justice dans la galaxie !");
                ActiverSabreLaser("bleu");
                break;

            case "Neutre":
                Debug.Log("Un être équilibré, ni Jedi ni Sith.");
                ActiverSabreLaser("vert");
                break;

            default:
                Debug.Log("Hmm... La Force est incertaine avec ce personnage.");
                ActiverSabreLaser("violet");
                break;
        }
    }

    // Méthode pour afficher le sabre laser selon la couleur
    void ActiverSabreLaser(string couleur)
    {
        Debug.Log("Activation du sabre laser " + couleur + " ⚔️");
        // Ici, vous pourriez activer des effets visuels dans Unity selon la couleur choisie !
    }
}

AnakinCounter.cs

using UnityEngine;
using System.Collections;

public class AnakinCounter : MonoBehaviour
{
    public int nombreEnfants = 0; // Compteur d'enfants affrontés
    public int limiteEnfants = 5;  // Limite d'enfants à atteindre pour la blague

    void Start()
    {
        StartCoroutine(CompterEnfants());
    }

    IEnumerator CompterEnfants()
    {
        Debug.Log("Anakin Skywalker compte les enfants...");

        while (nombreEnfants < limiteEnfants)
        {
            // Simuler l'affrontement avec un enfant
            nombreEnfants++;
            Debug.Log("J'ai affronté un enfant avec mon sabre laser... Nombre total : " + nombreEnfants);

            // Simuler une pause entre les affrontements
            yield return new WaitForSeconds(1); // Pause de 1 seconde pour simuler un affrontement
        }

        Debug.Log("Voilà, ça c'est fait.");
    }
}

CountdownDeathStar.cs

using UnityEngine;
using System.Collections;

public class CountdownDeathStar : MonoBehaviour
{
    public int countdownStart = 5; // Démarre le compte à rebours à 5 secondes

    void Start()
    {
        StartCoroutine(Countdown());
    }

    IEnumerator Countdown()
    {
        Debug.Log("Démarrage du compte à rebours pour la destruction de l'Étoile de la Mort...");

        // Utilisation d'une boucle for pour le compte à rebours
        for (int i = countdownStart; i > 0; i--)
        {
            Debug.Log("Temps restant avant la destruction : " + i + "...");
            yield return new WaitForSeconds(1); // Attendre 1 seconde entre chaque message
        }

        Debug.Log("BOUM ! L'Étoile de la Mort a explosé !");
    }
}

AlienMeeting.cs

using UnityEngine;
using System.Collections.Generic;

public class AlienMeeting : MonoBehaviour
{
    // Liste d'humains avec leurs traits caractéristiques
    public List<string> humains = new List<string> { "Bob", "Alice", "Charlie", "Diana" };

    void Start()
    {
        OrganiserReunion();
    }

    void OrganiserReunion()
    {
        Debug.Log("Les aliens se réunissent pour étudier les humains...");

        // Utilisation de foreach pour parcourir la liste des humains
        foreach (string humain in humains)
        {
            Debug.Log("Analysons l'humain : " + humain);

            // Simuler une analyse des caractéristiques humaines
            if (humain == "Bob")
            {
                Debug.Log(humain + " adore les pizzas... Même les aliens trouvent ça bizarre !");
            }
            else if (humain == "Alice")
            {
                Debug.Log(humain + " pense que les chats sont des extraterrestres !");
            }
            else if (humain == "Charlie")
            {
                Debug.Log(humain + " ne sait jamais où il a mis ses clés. Peut-être qu'un alien les a enlevées ?");
            }
            else if (humain == "Diana")
            {
                Debug.Log(humain + " dit que le café est la clé de la survie sur Terre !");
            }
        }

        Debug.Log("Conclusion : Les humains sont étranges, mais au moins, ils ont de la bonne nourriture !");
    }
}

RobotParty.cs

using UnityEngine;

public class RobotParty : MonoBehaviour
{
    void Start()
    {
        // Définissons quelques robots avec leurs caractéristiques
        bool robotA = true; // Robot A a une invitation
        bool robotB = false; // Robot B n'a pas d'invitation
        bool robotC = true; // Robot C a une invitation
        bool robotD = false; // Robot D n'a pas d'invitation

        // Utilisation des opérateurs logiques
        Debug.Log("Décisions des robots pour entrer à la fête :");

        // AND : Tous les robots doivent avoir une invitation pour entrer
        if (robotA && robotC)
        {
            Debug.Log("Robot A et Robot C : Entrez, vous êtes les bienvenus ! 🤖🎉");
        }
        else
        {
            Debug.Log("Robot A et Robot C : Désolé, il vous faut tous les deux une invitation !");
        }

        // OR : Au moins un robot doit avoir une invitation pour que l'autre puisse entrer
        if (robotA || robotB)
        {
            Debug.Log("Robot A ou Robot B : Au moins un d'entre vous peut entrer ! 🤖🎈");
        }

        // XOR : Un seul robot peut entrer, mais pas les deux
        if (robotA ^ robotB)
        {
            Debug.Log("Robot A et Robot B : L'un entre, l'autre reste dehors ! 🤖🚪");
        }
        else
        {
            Debug.Log("Robot A et Robot B : Vous devez décider qui entre !");
        }

        // NOR : Aucun robot n'a d'invitation
        if (!(robotA || robotB || robotC || robotD))
        {
            Debug.Log("Robot A, B, C et D : Personne n'a d'invitation, donc personne ne peut entrer ! 🤖🚫");
        }
        else
        {
            Debug.Log("Robot A, B, C et D : Au moins un d'entre vous a une invitation !");
        }

        // NAND : Pas tous les robots ont d'invitation
        if (!(robotA && robotB && robotC && robotD))
        {
            Debug.Log("Robot A, B, C et D : Pas tous les robots sont invités, quelqu'un peut entrer ! 🤖🕺");
        }

        // XNOR : Tous les robots ont soit une invitation, soit aucune
        if ((robotA && robotC) == (robotB && robotD))
        {
            Debug.Log("Robot A, B, C et D : Soit tous invités, soit tous exclus !");
        }
    }
}
EloiStree commented 1 week ago

https://openclassrooms.com/en/courses/5670356-learn-programming-with-c/6080936-select-the-proper-condition-to-control-your-program-flow

using UnityEngine;
using UnityEngine.UI; // Make sure to include this for UI components

public class BooleanExamplesWithTextArea : MonoBehaviour
{
    [TextArea(0,10)]
    public string textArea;  
    void Start()
    {
        // Create a StringBuilder to store the results
        System.Text.StringBuilder results = new System.Text.StringBuilder();

        // Evaluate boolean expressions and append to results
        results.AppendLine("2 == 2: " + (2 == 2)); // true
        results.AppendLine("2 == 3: " + (2 == 3)); // false
        results.AppendLine("4 != 4: " + (4 != 4)); // false
        results.AppendLine("4 != 5: " + (4 != 5)); // true
        results.AppendLine("1 < 2: " + (1 < 2)); // true
        results.AppendLine("1 < 1: " + (1 < 1)); // false
        results.AppendLine("1 <= 1: " + (1 <= 1)); // true
        results.AppendLine("3 > 4: " + (3 > 4)); // false
        results.AppendLine("5 > 4: " + (5 > 4)); // true
        results.AppendLine("5 >= 4: " + (5 >= 4)); // true

        results.AppendLine("true && true: " + (true && true)); // true
        results.AppendLine("true && false: " + (true && false)); // false
        results.AppendLine("false && false: " + (false && false)); // false
        results.AppendLine("true || false: " + (true || false)); // true
        results.AppendLine("true || true: " + (true || true)); // true
        results.AppendLine("false || false: " + (false || false)); // false
        results.AppendLine("!true: " + (!true)); // false
        results.AppendLine("!false: " + (!false)); // true

        results.AppendLine("true && true && true: " + (true && true && true)); // true
        results.AppendLine("true && true && false: " + (true && true && false)); // false
        results.AppendLine("true || false || false: " + (true || false || false)); // true
        results.AppendLine("false || false || false: " + (false || false || false)); // false
        results.AppendLine("!true && false: " + (!true && false)); // false
        results.AppendLine("!(true && false): " + (!(true && false)); // true
        results.AppendLine("4 < 3 || 4 >= 4: " + (4 < 3 || 4 >= 4)); // true
        results.AppendLine("(!(1 == 2) || 3 != 3) && 35 > 34: " + (!(1 == 2) || 3 != 3) && 35 > 34); // true

        // Display results in the TextArea
        textArea.text = results.ToString();
    }
}
EloiStree commented 1 week ago

enum


public enum BiereBelge
{
    Blonde,
    Brune,
    Blanche,
    Ambrée
}

public void CommanderBiere(BiereBelge biere)
{
    switch (biere)
    {
        case BiereBelge.Blonde:
            Console.WriteLine("Une blonde, parfaite pour une soirée ensoleillée !");
            break;
        case BiereBelge.Brune:
            Console.WriteLine("Une brune, pour savourer chaque gorgée !");
            break;
        case BiereBelge.Blanche:
            Console.WriteLine("Une blanche, légère et rafraîchissante !");
            break;
        case BiereBelge.Ambrée:
            Console.WriteLine("Une ambrée, riche en saveurs !");
            break;
        default:
            Console.WriteLine("Je ne connais pas ce type de bière... Peut-être une limonade ?");
            break;
    }
}
EloiStree commented 1 week ago

In C#, the foreach loop is a convenient way to iterate over a collection such as arrays, lists, or dictionaries. Here's a brief overview and a few examples of how to use it in Unity3D.

Basic Syntax of foreach

The syntax of a foreach loop is:

foreach (var item in collection)
{
    // Code to execute for each item
}

Example 1: Iterating Over an Array

Here's an example of using foreach to iterate over an array of integers in Unity3D:

using UnityEngine;

public class ForeachExample : MonoBehaviour
{
    void Start()
    {
        int[] numbers = { 1, 2, 3, 4, 5 };

        foreach (int number in numbers)
        {
            Debug.Log(number);
        }
    }
}

In this example, the Start method logs each number in the numbers array to the console.

Example 2: Iterating Over a List

You can also use foreach to iterate over a List:

using UnityEngine;
using System.Collections.Generic;

public class ListForeachExample : MonoBehaviour
{
    void Start()
    {
        List<string> fruits = new List<string> { "Apple", "Banana", "Cherry" };

        foreach (string fruit in fruits)
        {
            Debug.Log(fruit);
        }
    }
}

In this case, the Start method logs each fruit name in the fruits list.

Example 3: Iterating Over a Dictionary

You can iterate over key-value pairs in a Dictionary as follows:

using UnityEngine;
using System.Collections.Generic;

public class DictionaryForeachExample : MonoBehaviour
{
    void Start()
    {
        Dictionary<string, int> scores = new Dictionary<string, int>
        {
            { "Player1", 100 },
            { "Player2", 200 },
            { "Player3", 300 }
        };

        foreach (KeyValuePair<string, int> score in scores)
        {
            Debug.Log(score.Key + ": " + score.Value);
        }
    }
}

In this example, the Start method logs each player's name and their corresponding score from the scores dictionary.

Example 4: Iterating Over Components

In Unity, you can use foreach to iterate over components attached to GameObjects. Here's an example that logs the names of all MeshRenderer components in the scene:

using UnityEngine;

public class ComponentForeachExample : MonoBehaviour
{
    void Start()
    {
        // Find all MeshRenderer components in the scene
        MeshRenderer[] renderers = FindObjectsOfType<MeshRenderer>();

        foreach (MeshRenderer renderer in renderers)
        {
            Debug.Log(renderer.name);
        }
    }
}

This script finds all MeshRenderer components in the scene and logs their names to the console.

Summary

The foreach loop is a powerful and straightforward way to iterate through collections in C#. In Unity3D, it's especially useful for processing arrays, lists, and dictionaries, as well as iterating over components or GameObjects.

EloiStree commented 1 week ago

https://openclassrooms.com/en/courses/5670356-learn-programming-with-c/6080961-manage-errors-and-exceptions-within-your-program

using UnityEngine;

public class ExampleScript : MonoBehaviour
{
    public GameObject myObject;

    void Start()
    {
        try
        {
            // Trying to access a component of myObject
            Rigidbody rb = myObject.GetComponent<Rigidbody>();
            // Perform operations with rb
            rb.AddForce(Vector3.up * 10f);
        }
        catch (System.NullReferenceException ex)
        {
            Debug.LogError("Darth Vader: 'You lack faith in your references!' " + ex.Message);
            Debug.LogError("Please assign myObject in the inspector!");
        }
    }
}

using UnityEngine;

public class AnswerToEverything : MonoBehaviour
{
    void Start()
    {
        try
        {
            // Attempting to get the answer to life, the universe, and everything
            GetTheAnswer();
        }
        catch (System.NotImplementedException ex)
        {
            Debug.LogError("Machine: 'I’m sorry, the answer is not implemented yet!' " + ex.Message);
        }
    }

    void GetTheAnswer()
    {
        // Uncomment the line below to simulate a NotImplementedException
        // throw new System.NotImplementedException("The answer to life, the universe, and everything is 42!");

        Debug.Log("42 is the answer to life, the universe, and everything!");
    }
}
EloiStree commented 1 week ago

https://openclassrooms.com/en/courses/5670356-learn-programming-with-c/6081006-a-closer-look-into-methods

Cette page est parfaite sur les méthodes. Il faut just y aller.

EloiStree commented 1 week ago

Unity C# Calculette with Operator Overloading and Unit Testing

This document provides a complete implementation of a simple calculator in Unity using C#, which includes operator overloading and unit testing with assertions.


using UnityEngine;

public class Calculette : MonoBehaviour
{
    // Method for addition
    public static int Sum(int a, int b)
    {
        return a + b;
    }

    // Method for subtraction
    public static int Sub(int a, int b)
    {
        return a - b;
    }

    // Method for multiplication
    public static int Mul(int a, int b)
    {
        return a * b;
    }

    // Method for division
    public static double Div(int a, int b)
    {
        if (b == 0)
        {
            throw new DivideByZeroException("Cannot divide by zero."); // Handle division by zero
        }
        return (double)a / b; // Return double for precision
    }
}

using UnityEngine;

public class CalculetteAssertionTest : MonoBehaviour
{
    void Start()
    {
        TestSum();
        TestSub();
        TestMul();
        TestDiv();
    }

    void TestSum()
    {
        int result = Calculette.Sum(1, 5);
        Debug.Assert(result == 6, "Sum assertion failed");
        Debug.Log("Sum works Ok");
    }

    void TestSub()
    {
        int result = Calculette.Sub(10, 8);
        Debug.Assert(result == 2, "Sub assertion failed");
        Debug.Log("Sub works Ok");
    }

    void TestMul()
    {
        int result = Calculette.Mul(3, 4);
        Debug.Assert(result == 12, "Mul assertion failed");
        Debug.Log("Mul works Ok");
    }

    void TestDiv()
    {
        try
        {
            double result = Calculette.Div(10, 2);
            Debug.Assert(result == 5.0, "Div assertion failed");
            Debug.Log("Div works Ok");
        }
        catch (DivideByZeroException ex)
        {
            Debug.Log(ex.Message);
        }
    }
}

using NUnit.Framework;

[TestFixture]
public class CalculetteTests
{
    [Test]
    public void TestSum()
    {
        Assert.AreEqual(6, Calculette.Sum(1, 5));
    }

    [Test]
    public void TestSub()
    {
        Assert.AreEqual(2, Calculette.Sub(10, 8));
    }

    [Test]
    public void TestMul()
    {
        Assert.AreEqual(12, Calculette.Mul(3, 4));
    }

    [Test]
    public void TestDiv()
    {
        Assert.AreEqual(5.0, Calculette.Div(10, 2));
    }

    [Test]
    public void TestDivByZero()
    {
        Assert.Throws<DivideByZeroException>(() => Calculette.Div(10, 0));
    }
}

1. MyNumber Class

The MyNumber class represents a number and provides operator overloading for addition, subtraction, multiplication, and division.

using UnityEngine;

public class MyNumber
{
    public int Value { get; private set; }

    // Constructor
    public MyNumber(int value)
    {
        Value = value;
    }

    // Operator overloading for addition
    public static MyNumber operator +(MyNumber a, MyNumber b)
    {
        return new MyNumber(a.Value + b.Value);
    }

    // Operator overloading for subtraction
    public static MyNumber operator -(MyNumber a, MyNumber b)
    {
        return new MyNumber(a.Value - b.Value);
    }

    // Operator overloading for multiplication
    public static MyNumber operator *(MyNumber a, MyNumber b)
    {
        return new MyNumber(a.Value * b.Value);
    }

    // Operator overloading for division
    public static MyNumber operator /(MyNumber a, MyNumber b)
    {
        if (b.Value == 0)
        {
            throw new DivideByZeroException("Cannot divide by zero.");
        }
        return new MyNumber(a.Value / b.Value);
    }

    // ToString override for better display
    public override string ToString()
    {
        return Value.ToString();
    }
}

2. Calculette Class

The Calculette class can remain empty if it's only used for demonstration, or it can be used for other calculations.

using UnityEngine;

public class Calculette : MonoBehaviour
{
    // This class can be used for other calculations if needed, or removed entirely.
}

3. MyNumberTest Class

This class tests the overloaded operators using assertions.

using UnityEngine;

public class MyNumberTest : MonoBehaviour
{
    void Start()
    {
        TestOperatorOverloading();
    }

    void TestOperatorOverloading()
    {
        MyNumber a = new MyNumber(10);
        MyNumber b = new MyNumber(5);

        // Test Addition
        MyNumber sumResult = a + b;
        Debug.Assert(sumResult.Value == 15, "Addition failed");
        Debug.Log($"Addition: {a} + {b} = {sumResult}");

        // Test Subtraction
        MyNumber subResult = a - b;
        Debug.Assert(subResult.Value == 5, "Subtraction failed");
        Debug.Log($"Subtraction: {a} - {b} = {subResult}");

        // Test Multiplication
        MyNumber mulResult = a * b;
        Debug.Assert(mulResult.Value == 50, "Multiplication failed");
        Debug.Log($"Multiplication: {a} * {b} = {mulResult}");

        // Test Division
        MyNumber divResult = a / b;
        Debug.Assert(divResult.Value == 2, "Division failed");
        Debug.Log($"Division: {a} / {b} = {divResult}");

        // Test Division by zero
        try
        {
            MyNumber divByZeroResult = a / new MyNumber(0);
        }
        catch (DivideByZeroException ex)
        {
            Debug.Log("Div by zero test: " + ex.Message);
        }
    }
}

4. Unity Test Framework Example

For structured testing using Unity's testing framework, create a separate test script.

using NUnit.Framework;

[TestFixture]
public class MyNumberTests
{
    [Test]
    public void TestAddition()
    {
        MyNumber a = new MyNumber(10);
        MyNumber b = new MyNumber(5);
        MyNumber result = a + b;
        Assert.AreEqual(15, result.Value);
    }

    [Test]
    public void TestSubtraction()
    {
        MyNumber a = new MyNumber(10);
        MyNumber b = new MyNumber(5);
        MyNumber result = a - b;
        Assert.AreEqual(5, result.Value);
    }

    [Test]
    public void TestMultiplication()
    {
        MyNumber a = new MyNumber(10);
        MyNumber b = new MyNumber(5);
        MyNumber result = a * b;
        Assert.AreEqual(50, result.Value);
    }

    [Test]
    public void TestDivision()
    {
        MyNumber a = new MyNumber(10);
        MyNumber b = new MyNumber(5);
        MyNumber result = a / b;
        Assert.AreEqual(2, result.Value);
    }

    [Test]
    public void TestDivisionByZero()
    {
        MyNumber a = new MyNumber(10);
        MyNumber b = new MyNumber(0);
        Assert.Throws<DivideByZeroException>(() => a / b);
    }
}

How to Use in Unity

  1. Create the Scripts:

    • Create a new C# script named MyNumber.cs and paste the MyNumber class code.
    • Create another script named MyNumberTest.cs and paste the test class code.
    • Optionally, create a script named Calculette.cs for potential future use.
  2. Attach to GameObject:

    • Create an empty GameObject in your Unity scene.
    • Attach the MyNumberTest script to the GameObject.
  3. Run the Scene:

    • Press the Play button in Unity. You should see the results of the tests logged in the Console.
  4. Run Unit Tests:

    • Open the Test Runner window via Window > General > Test Runner.
    • Click Run All to execute the tests in the MyNumberTests class.

This setup allows you to effectively use operator overloading in a custom class and validate its functionality using both manual assertions in the Unity console and structured tests using the Unity Test Framework.

EloiStree commented 1 week ago

Next ^^ : Bien meilleur et plus direct https://www.w3schools.com/cs/index.php

EloiStree commented 1 week ago

image

Le plus amical pour apprendre C# https://synchronicales.eu/sdz/sdz/apprenez-a-developper-en-c.html Version PDF: SiteDuZeroC#.pdf

EloiStree commented 1 week ago