Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Array improperly loading

Discussion in 'Scripting' started by UnderworldGames, Nov 11, 2020.

  1. UnderworldGames

    UnderworldGames

    Joined:
    Oct 26, 2020
    Posts:
    11
    I have an array in my game that is set as active prior to pressing play (see fig.1) but as soon as I press play, it doesn't load properly (see fig.2). Each element is a prefab, and the prefabs all have the same settings, so I can't figure out why only some are loading. The Object Spawner script is what I use for it, and array was working just fine when I only had three elements, but when I added the fourth it stopped working properly. Can anyone see what I'm doing wrong?

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class ObjectSpawner : MonoBehaviour
    6. {
    7.     public GameObject player;
    8.     public GameObject[] trianglePrefabs;
    9.     private Vector3 spawnObstaclePosition;
    10.  
    11.    
    12.     // Update is called once per frame
    13.     void Update()
    14.     {
    15.         float distanceToHorizon = Vector3.Distance(player.gameObject.transform.position, spawnObstaclePosition);
    16.         if (distanceToHorizon < 120)
    17.         {
    18.             SpawnTriangles();
    19.         }
    20.     }
    21.     void SpawnTriangles()
    22.     {
    23.         spawnObstaclePosition = new Vector3(0, 0, spawnObstaclePosition.z + 30);
    24.         Instantiate(trianglePrefabs[(Random.Range(0, trianglePrefabs.Length))], spawnObstaclePosition, Quaternion.identity);
    25.     }
    26. }
    27.  
     

    Attached Files:

  2. bobisgod234

    bobisgod234

    Joined:
    Nov 15, 2016
    Posts:
    1,042
    The blue box disappears from elements 1 and 4 on play, so from the look of it, element 1 and 3 are not actually prefabs. They seem to be referencing an instance of a prefab in the scene, rather than the prefab itself that is in the project view.
     
    UnderworldGames likes this.
  3. UnderworldGames

    UnderworldGames

    Joined:
    Oct 26, 2020
    Posts:
    11
    You are a hero, this is exactly what the problem was. Many thanks!