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

Loading prefabs in an array

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

  1. UnderworldGames

    UnderworldGames

    Joined:
    Oct 26, 2020
    Posts:
    11
    I have a spawning script that spawns a random prefab from an array of prefabs. Element 7 (Floater, Figure1) will load if it is selected at the beginning of the game(Figure2), but when it should be randomly selected later on, the area in game where it should spawn is instead a long stretch of empty space (Figure3). The only difference between the Floater prefab and the triangle prefabs is that the Floater is one object and the triangles are three objects, and that the Floater has movement left and right.

    The problem is that the coding I used tells the z axis of the Vector3 to be 0, which puts it behind the player (which another script tells it to be destroyed). So how can I get the z axis to stay wherever it is spawned?

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class Floater : MonoBehaviour
    6. {
    7.  
    8.     private GameObject player;
    9.  
    10.     private Vector3 pos1 = new Vector3(-2, 0, 0);
    11.     private Vector3 pos2 = new Vector3(2, 0, 0);
    12.     public float speed = 1.0f;
    13.  
    14.     // Start is called before the first frame update
    15.     void Start()
    16.     {
    17.         player = GameObject.FindGameObjectWithTag("Player");
    18.     }
    19.  
    20.     // Update is called once per frame
    21.     void Update()
    22.     {
    23.         if (gameObject.transform.position.z < player.transform.position.z - 15)
    24.         {
    25.             Destroy(gameObject);
    26.         }
    27.  
    28.         transform.position = Vector3.Lerp(pos1, pos2, Mathf.PingPong(Time.time * speed, 1.0f));
    29.  
    30.     }
     

    Attached Files:

  2. bobisgod234

    bobisgod234

    Joined:
    Nov 15, 2016
    Posts:
    1,042
    Try:

    Code (CSharp):
    1.     void Start()
    2.     {
    3.         player = GameObject.FindGameObjectWithTag("Player");
    4.         pos1.z = transform.position.z;
    5.         pos2.z = transform.position.z;
    6.     }
    7.  
     
    UnderworldGames likes this.
  3. UnderworldGames

    UnderworldGames

    Joined:
    Oct 26, 2020
    Posts:
    11
    This worked! Thank you so much!