Spawner

Sur cette page tu apprendras comment crƩer un spawner, objet essentiel Ơ ton projet.

Qu’est-ce qu’un spawner?

Le spawner est un objet ou une position dans un jeu qui peut gĆ©nĆ©rer d’autre Ć©lĆ©ments (ennemis, items, etc)

Il utilise le code ā€œInstantiateā€ pour cela.

L’avantage d’instantiate est qu’on peut gĆ©nĆ©rer les objets dans la direction ou le spawner pointe, ce qui permet de diriger les Ć©lĆ©ments facilement.

Instantiate(OBJET A FAIRE APPARAITRE, POSITION D’APPARITION, DIRECTION DE L’OBJET);

Ce code s’utilise ou l’on veut, on peut le dĆ©clencher avec un input, une collision, etc.

Le script

Ce script est un exemple de spawner qui utilise une liste d’objets, pour en spawner un au hasard toutes les X secondes, avec X qui varie legerement a chaque fois (pour garder le joueur en alerte)

Ā 
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Spawner : MonoBehaviour
{
Ā  Ā  public GameObject[] objets_a_spawner;
Ā  Ā  public float Delay;
Ā  Ā  public float variationDelay;
Ā  Ā  float timer;
Ā  Ā  void Start()
Ā  Ā  {
Ā  Ā  Ā  Ā  timer = 5f; //on dĆ©cide d’un temps avant le premier spawn si on veut
Ā Ā Ā Ā }
Ā  Ā  void Update()
Ā  Ā  {
Ā  Ā  Ā  Ā  timer -= Time.deltaTime;
Ā  Ā  Ā  Ā  if (timer <= 0)
Ā  Ā  Ā  Ā  {
Ā  Ā  Ā  Ā  Ā  Ā  Spawn(); //on lance la generation avec une fonction
            timer = Delay + Random.Range(-variationDelay, variationDelay); //on spawn avec un delai legerement aléatoire
Ā Ā Ā Ā Ā Ā Ā Ā }
Ā  Ā  }
Ā  Ā  void Spawn()
Ā  Ā  {
Ā  Ā  Ā  Ā  int randomIndex = Mathf.RoundToInt(Random.Range(0, objets_a_spawner.Length)); //on choisit un des objets de la liste
Ā Ā Ā Ā Ā Ā Ā Ā GameObject vase = Instantiate(canards[randomIndex], transform.position, transform.rotation); //on genĆØre l’objet choisi
Ć  la position et dans la direction du spawner
Ā Ā Ā Ā }
}

Retour en haut