Open EloiStree opened 1 week ago
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 |
+
-
*
/
%
// 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();
// 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 });
// 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;
https://openclassrooms.com/en/courses/5670356-learn-programming-with-c/6080891-manage-complexity-with-the-right-collection
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;
}
// 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
}
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
}
}
}
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;
}
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!");
}
}
}
ToUpper()
Converts all characters in a string to uppercase.
string text = "hello world";
Debug.Log(text.ToUpper()); // Output: "HELLO WORLD"
ToLower()
Converts all characters in a string to lowercase.
string text = "HELLO WORLD";
Debug.Log(text.ToLower()); // Output: "hello world"
Replace()
Replaces all occurrences of a specified substring with another substring.
string text = "hello world";
Debug.Log(text.Replace("world", "Unity")); // Output: "hello Unity"
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
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"
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"
Contains()
Checks if a string contains a specified substring.
string text = "hello world";
Debug.Log(text.Contains("world")); // Output: True
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
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"
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"
Insert()
Inserts a string at a specified index.
string text = "hello world";
Debug.Log(text.Insert(6, "Unity ")); // Output: "hello Unity world"
Length
PropertyReturns the number of characters in the string.
string text = "hello world";
Debug.Log(text.Length); // Output: 11
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!"
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!"
Compare()
, Equals()
, and ==
Compare()
compares two strings lexicographically.Equals()
checks for equality between two strings.==
also checks for equality but is simpler to use.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)
ToCharArray()
Converts a string to a character array.
string text = "hello";
char[] chars = text.ToCharArray();
Debug.Log(chars[1]); // Output: "e"
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
Abs()
Returns the absolute value of a number.
float value = -10.5f;
Debug.Log(Mathf.Abs(value)); // Output: 10.5
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
Clamp()
Clamps a value between a minimum and maximum value.
float value = 15f;
Debug.Log(Mathf.Clamp(value, 0f, 10f)); // Output: 10
Clamp01()
Clamps a value between 0 and 1, often useful for normalizing.
float value = 1.5f;
Debug.Log(Mathf.Clamp01(value)); // Output: 1
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
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
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
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
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)
Sign()
Returns the sign of a number as -1, 1, or 0.
float value = -10f;
Debug.Log(Mathf.Sign(value)); // Output: -1
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
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
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)
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
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
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)
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)
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
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)
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
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");
}
}
void Start()
{
PrintMessage("Hello, Unity!");
}
void PrintMessage(string message)
{
Debug.Log(message);
}
void Start()
{
int result = AddNumbers(3, 4);
Debug.Log("Sum: " + result); // Output: "Sum: 7"
}
int AddNumbers(int a, int b)
{
return a + b;
}
void Update()
{
MoveObject(Vector3.up);
}
void MoveObject(Vector3 direction)
{
transform.position += direction * Time.deltaTime;
}
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;
}
void Start()
{
ChangeColor(Color.red);
}
void ChangeColor(Color color)
{
GetComponent<Renderer>().material.color = color;
}
public AudioSource audioSource;
public AudioClip soundClip;
void Start()
{
PlaySound(soundClip);
}
void PlaySound(AudioClip clip)
{
audioSource.PlayOneShot(clip);
}
int power = 9001; if (power > 9000) { Debug.Log("Power level is over 9000!"); }
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 !
}
}
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 !
}
}
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.");
}
}
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é !");
}
}
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 !");
}
}
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 !");
}
}
}
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();
}
}
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;
}
}
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.
foreach
The syntax of a foreach
loop is:
foreach (var item in collection)
{
// Code to execute for each item
}
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.
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.
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.
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.
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.
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!");
}
}
Cette page est parfaite sur les méthodes. Il faut just y aller.
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));
}
}
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();
}
}
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.
}
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);
}
}
}
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);
}
}
Create the Scripts:
MyNumber.cs
and paste the MyNumber
class code.MyNumberTest.cs
and paste the test class code.Calculette.cs
for potential future use.Attach to GameObject:
MyNumberTest
script to the GameObject.Run the Scene:
Run Unit Tests:
Window
> General
> Test Runner
.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.
Next ^^ : Bien meilleur et plus direct https://www.w3schools.com/cs/index.php
Le plus amical pour apprendre C# https://synchronicales.eu/sdz/sdz/apprenez-a-developper-en-c.html Version PDF: SiteDuZeroC#.pdf
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