简体   繁体   中英

Unity Obstacle generator for endless runner

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

public class ObsSpawner : MonoBehaviour
{
    
    public List<GameObject> groundSpawner;
    [SerializeField] GameObject coinPrefab;
    [SerializeField] GameObject obstaclePrefab;

    private void Start () {
        groundSpawner = GameObject.FindObjectOfType<GameObject>();
    }

    public void SpawnObstacle ()
    {
        // Choose a random point to spawn the obstacle
        int obstacleSpawnIndex = Random.Range(2, 5);
        Transform spawnPoint = transform.GetChild(obstacleSpawnIndex).transform;

        // Spawn the obstace at the position
        Instantiate(obstaclePrefab, spawnPoint.position, Quaternion.identity, transform);
    }
}

Unity gives me the error: Cannot implicitly convert type UnityEngine.GameObject to System.Collections.Generic.List<UnityEngine.GameObject> . If someone could help me please.

This is a fairly simple, but common mistake.

public List<GameObject> groundSpawner;
private void Start () {
    groundSpawner = GameObject.FindObjectOfType<GameObject>();
}

Should be:

public GameObject[] groundSpawner;
private void Start () {
    groundSpawner = FindObjectsOfType<GameObject>();
}

Note the 's' in FindObjectsOfType and the return type of T[] , not List<T> . You also just call it on the local Component as it's not a static method.

Here's the Unity docs for further reading.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM