Skip to content
Learni
Voir tous les tutoriels
Unity

Comment créer son premier jeu 2D Unity en 2026

Read in English

Introduction

Unity est le moteur de jeu le plus populaire pour les débutants et pros, powering plus de 50% des jeux mobiles en 2026. Ce tutoriel vous guide pas à pas pour créer votre premier jeu 2D : un carré bleu (joueur) qui se déplace avec les flèches, collecte des pièces jaunes (+1 score) et affiche le total en haut. Pas de fluff : on installe, on code, on teste. À la fin, vous aurez un executable jouable. Pourquoi c'est crucial ? Unity gère physique, rendu et build multiplateforme sans boilerplate. Imaginez comme assembler un puzzle : la scène est votre planche, les scripts vos pièces mobiles. Durée estimée : 45 min. Prêt à shipper votre premier jeu ? (128 mots)

Prérequis

  • Unity Hub 3.10+ (téléchargez sur unity.com)
  • Unity Editor 2023.2 LTS ou 6000.0 (via Hub)
  • Connaissances basiques C# (variables, if/else)
  • Windows/Mac/Linux récent
  • VS Code ou Visual Studio (pour éditer scripts)

Installer Unity et créer le projet

terminal-install.sh
# 1. Téléchargez Unity Hub depuis unity.com
# 2. Installez Unity Editor 2023.2 LTS via Hub > Installs > Add
# 3. Créez projet :
unityhub://2023.2.20f1/2d/core
# Ou via interface Hub : New Project > 2D Core Template > Nom: 'MonPremierJeu' > Create

Ces commandes/instructions lancent Unity Hub pour installer l'éditeur LTS stable et créer un template 2D optimisé (Camera orthographique, Canvas UI prêt). Évitez les versions preview : elles crashent souvent sur projets débutants. Le template inclut déjà Physics 2D.

Configurer la scène principale

Ouvrez Scene (double-clic dans Project > Assets > Scenes > SampleScene).

  1. Hierarchy : Supprimez Sample Cube. Right-click > 2D Object > Sprite > Square → renommez 'Player'. Position (0,0,0), Scale (0.5,0.5,1).
  2. Ajoutez Rigidbody2D (Component > Physics 2D > Rigidbody2D) : Gravity Scale = 0 (pas de chute).
  3. Ajoutez BoxCollider2D : Is Trigger = false.
Créez 'Coin' : Right-click > 2D Object > Sprite > Circle, Scale (0.3,0.3,1), Position (3,0,0). Ajoutez CircleCollider2D (Is Trigger = true).

Ajoutez Camera fond noir : Main Camera > Background = Solid Color > Noir. Sauvegardez Ctrl+S.

Script de mouvement du joueur

Assets/Scripts/PlayerController.cs
using UnityEngine;

public class PlayerController : MonoBehaviour
{
    [SerializeField] private float speed = 5f;
    private Rigidbody2D rb;

    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }

    void Update()
    {
        float horizontal = Input.GetAxis("Horizontal");
        float vertical = Input.GetAxis("Vertical");
        Vector2 movement = new Vector2(horizontal, vertical) * speed;
        rb.velocity = movement;
    }
}

Ce script attache au Player : lit les inputs flèches/WASD via GetAxis (smooth, -1 à +1), applique vitesse à Rigidbody2D pour physique fluide. [SerializeField] permet éditer speed dans Inspector sans recompiler. Piège : Oublier rb = GetComponent() crash en Start(). Testez : Play, bougez le carré !

Attacher le script et tester mouvement

Attachez : Sélectionnez Player > Add Component > tapez 'PlayerController' > attachez le script. Speed=5 dans Inspector.

Test : Play (Ctrl+P). Flèches = déplacement. Arrêt = friction auto Rigidbody.

Améliorez : Ajoutez limites écran. Window > Analysis > Physics Debugger (voir colliders verts).

Script de collecte de pièces

Assets/Scripts/Coin.cs
using UnityEngine;

public class Coin : MonoBehaviour
{
    [SerializeField] private int value = 1;

    private void OnTriggerEnter2D(Collider2D other)
    {
        if (other.CompareTag("Player"))
        {
            GameManager.Instance.AddScore(value);
            Destroy(gameObject);
        }
    }
}

Sur Coin (CircleCollider Is Trigger=true) : OnTriggerEnter2D détecte collision avec tag 'Player'. Ajoute score via singleton GameManager, détruit pièce. CompareTag est optimisé vs == "Player". Piège : Oublier tag Player (Hierarchy > Player > Tag > Add Tag > Player > assigner).

Préparer UI Score et tag Player

  1. Tag Player : Tag dropdown > + > Player > assignez à Player.
  2. UI Score : Right-click Canvas > UI > Text - TextMeshPro. Renommez 'ScoreText', Anchor Top-Center, Text="Score: 0", Font Size=36.
  3. Positionnez à (0, haut écran). Play : mouvement OK, collision Player-Coin ignore score (prochain script).

Script GameManager pour score

Assets/Scripts/GameManager.cs
using UnityEngine;
using TMPro;

public class GameManager : MonoBehaviour
{
    public static GameManager Instance;
    [SerializeField] private TextMeshProUGUI scoreText;
    private int score = 0;

    void Awake()
    {
        if (Instance == null)
        {
            Instance = this;
            DontDestroyOnLoad(gameObject);
        }
        else
        {
            Destroy(gameObject);
        }
    }

    public void AddScore(int points)
    {
        score += points;
        scoreText.text = "Score: " + score;
    }
}

Singleton persistant : Awake gère unique Instance. AddScore update UI TMPro. [SerializeField] lie ScoreText dans Inspector (drag depuis Hierarchy). Piège : Oublier TMPro import ou drag → NullRef. Créez Empty GameObject 'GameManager', attachez script, liez ScoreText.

Script respawn pièces infini

Assets/Scripts/CoinSpawner.cs
using UnityEngine;

public class CoinSpawner : MonoBehaviour
{
    [SerializeField] private GameObject coinPrefab;
    [SerializeField] private float spawnInterval = 2f;
    [SerializeField] private Vector2 spawnArea = new Vector2(8f, 4f);

    void Start()
    {
        InvokeRepeating(nameof(SpawnCoin), 1f, spawnInterval);
    }

    void SpawnCoin()
    {
        Vector2 pos = new Vector2(
            Random.Range(-spawnArea.x/2, spawnArea.x/2),
            Random.Range(-spawnArea.y/2, spawnArea.y/2)
        );
        Instantiate(coinPrefab, pos, Quaternion.identity);
    }
}

Attachez à Empty 'Spawner' (Position 0,0). Drag Coin comme prefab (drag Coin > Project > Assets/Prefabs). SpawnArea définit zone (-4 à +4 X/Y). InvokeRepeating = timer fiable. Piège : Pas de prefab → Instantiate null. Faites Coin prefab d'abord.

Finaliser : Prefab Coin et spawner

Prefab Coin : Drag Coin de Hierarchy vers Assets/Prefabs. Delete original.

Spawner : Right-click Hierarchy > Empty > 'CoinSpawner'. Attachez script, drag Prefab Coin, Interval=2, Area=(10,5). Play : Pièces spawnent, collectez, score ↑ !

Polish : Ajoutez Sprite Renderer couleur (Player=bleu, Coin=jaune). Window > Package Manager > 2D Sprite si besoin.

Build et exporter le jeu

terminal-build.sh
# Via Unity Editor :
# File > Build Settings > PC/Mac/Linux Standalone > Add Open Scenes
# Player Settings > Company/Name/Product
# Build > Choisir dossier 'Builds'

# Ou CLI (optionnel) :
/Applications/Unity/Hub/Editor/2023.2.20f1/Unity.app/Contents/MacOS/Unity \
-buildTarget Win64 -executeMethod AutoBuilder.BuildPlayer -quit -batchmode

Build Settings compile exe jouable. Ajoutez icône (Player Settings > Icon). Testez hors Editor. Piège : Oublier scenes → build vide. CLI pour CI/CD.

Bonnes pratiques

  • Version Control : Git init, .gitignore Unity (Assets, Library, etc.). Commit après chaque script.
  • Layers/Physics : Player layer 'Player', Coin 'Collectible' → Layer Collision Matrix pour optimiser.
  • Prefabs : Tout réutilisable en prefab (Player, Coin, UI).
  • Input System : Migrez vers new Input System (Package Manager) pour multiplateforme.
  • Profile CPU : Window > Analysis > Profiler pour <16ms/frame.

Erreurs courantes à éviter

  • NullReference : Vérifiez GetComponent() et drag Inspector. Console > Clear on Play.
  • Physique glitch : FixedUpdate pour forces, Update pour input. Gravity Scale=0 si pas besoin.
  • UI non visible : Canvas Scaler > UI Scale Mode = Scale With Screen Size.
  • Build échoue : Scripting Backend = IL2CPP pour perf, Api Compatibility .NET Standard 2.1.

Pour aller plus loin