I am using Unity in C# to code a game similar to Google's Dinosaur Run where random obstacles are spawned in the player's path which they need to jump to dodge. I have 6 different prefabs (with animations) for my obstacles which use Polygon Colliders to detect collisions. How can I use an array to randomly select one of these obstacle prefabs to spawn them at various distances apart?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ObstacleController : MonoBehaviour
    private Sprite[] sprites;

    public int Type { get; set; }

    private SpriteRenderer spriteRenderer;

    private PolygonCollider2D polygonCollider2D;

    public void Initialise()
        spriteRenderer = GetComponent<SpriteRenderer>();
        polygonCollider2D = GetComponent<PolygonCollider2D>();

        int type = Random.Range(0, sprites.Length);

        Type = type;
        spriteRenderer.sprite = sprites[type];

Above is the code I have so far which only allows me to have sprites as obstacles whereas I want to use prefabs with set dimensions and animation properties.

  • \$\begingroup\$ You can use GameObject[] instead of Sprite[] to hold your prefabs \$\endgroup\$
    – Zibelas
    Aug 16, 2021 at 12:02

1 Answer 1


use this,

[Serializefield] GameObject [] prefabs;
int type = Random.Range (0, sprites.Length);
float spwanRangeX = 10f; // desired value
Vector3 spwanPos = new Vector3 (Random.Range(spwanRangeX,-spawnRangeX),0,0);
Instantiate (prefabs[type], spawnPos , prefabs[type].transform.rotation);
  • 1
    \$\begingroup\$ OP needs a solution that works with prefabs rather than sprites, but this answer is not addressing such issues. You could edit and expand it as needed. \$\endgroup\$
    – liggiorgio
    Aug 16, 2021 at 14:21
  • \$\begingroup\$ I'm having some syntax errors when I use this script - Assets\Scripts\ObstacleController.cs(12,25): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) Assets\Scripts\ObstacleController.cs(12,30): error CS1001: Identifier expected Assets\Scripts\ObstacleController.cs(12,41): error CS1001: Identifier expected Assets\Scripts\ObstacleController.cs(12,56): error CS1003: Syntax error, ',' expected \$\endgroup\$ Aug 20, 2021 at 0:56
  • \$\begingroup\$ Drag prefabs into the prefabs array slot in inspector \$\endgroup\$ Aug 21, 2021 at 6:59

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .