1. GameObject.
SetActive(bool)
Permet d'activer ou désactiver un GameObject dans la scène.
Exemple :
public GameObject target;
void Update()
if (Input.GetKeyDown(KeyCode.Space))
target.SetActive(!target.activeSelf);
2. Mathf.Lerp(float a, float b, float t)
Effectue une interpolation linéaire entre deux valeurs float.
Exemple :
float currentValue = 0f;
float targetValue = 1f;
float speed = 2f;
void Update()
currentValue = Mathf.Lerp(currentValue, targetValue, Time.deltaTime * speed);
3. Time.deltaTime
Représente le temps écoulé entre deux frames. Permet un mouvement fluide.
Exemple :
float speed = 5f;
void Update()
transform.Translate(Vector3.forward * speed * Time.deltaTime);
4. Physics.Raycast
Lance un rayon invisible pour détecter des objets avec un collider.
Exemple :
void Update()
if (Physics.Raycast(transform.position, transform.forward, out RaycastHit hit, 10f))
Debug.Log("Touché : " + hit.collider.name);
5. Vector3.Lerp(Vector3 a, Vector3 b, float t)
Interpolation fluide entre deux positions.
Exemple :
public Transform pointA;
public Transform pointB;
public float speed = 2f;
float t = 0f;
void Update()
t += Time.deltaTime * speed;
transform.position = Vector3.Lerp(pointA.position, pointB.position, t);
6. Debug.Log
Affiche un message dans la console Unity.
Exemple :
void Start()
Debug.Log("Le jeu commence !");
void Update()
if (Input.GetKeyDown(KeyCode.Space))
Debug.Log("Espace a été pressée !");
Debug.Log("Position du joueur : " + transform.position);
7. Instantiate (Créer un objet)
Créer un objet dans la scène à partir d'un prefab.
Exemple :
public GameObject prefab;
public Transform spawnPoint;
void Update()
if (Input.GetKeyDown(KeyCode.Space))
{
Instantiate(prefab, spawnPoint.position, spawnPoint.rotation);
8. OnTriggerEnter (Détection sans physique)
Détecte l'entrée dans un collider en mode "Is Trigger".
Exemple :
void OnTriggerEnter(Collider other)
Debug.Log("Collision avec : " + other.name);
Note : L'objet doit avoir un Collider (Is Trigger activé) + un Rigidbody.
9. Coroutine avec WaitForSeconds
Permet de faire une pause dans l'exécution d'une fonction.
Exemple :
void Start()
StartCoroutine(WaitAndPrint());
IEnumerator WaitAndPrint()
Debug.Log("Attente de 3 secondes...");
yield return new WaitForSeconds(3f);
Debug.Log("C'est fini !");
}
10. Exercice : Mini système de projectile
Objectif :
- Appuyer sur Espace pour lancer un projectile
- Le projectile se déplace vers l'avant
- Il se détruit après 2 secondes
- Il détecte les collisions avec OnTriggerEnter
Projectile.cs :
void Start()
GetComponent<Rigidbody>().AddForce(transform.forward * 500f);
Destroy(gameObject, 2f);
void OnTriggerEnter(Collider other)
Debug.Log("Impact avec : " + other.name);
Spawner.cs :
public GameObject projectilePrefab;
public Transform spawnPoint;
void Update()
if (Input.GetKeyDown(KeyCode.Space))
Instantiate(projectilePrefab, spawnPoint.position, spawnPoint.rotation);