I have a list of GameObject prefabs that are off-camera in the scene. Each Prefab has its own spawnPoint GameObject. I want to instantiate a random prefab from the list at its spawnPoint, but I can’t figure out how to do it. It just spawns clones over where it already exists in the scene. I have tried the spawnPoint as a GameObject, Vector2, Vector3, and a Transform. Nothing works, and I would really appreciate some help/advice.
How do reference or get the component of the spawnPoint
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Spawn : MonoBehaviour
{
public List<GameObject> EnviromentObjects = new List<GameObject>();
public int randomListObject;
void InstantiateRandomObject()
{
randomListObject = Random.Range(0, EnviromentObjects.Count);
Instantiate(EnviromentObjects[randomListObject], EnviromentObjects[randomListObject].GetComponent<spawnPoint>, Quaternion.identity);
}
}
Hi, from what you’re writing “I have a list of GameObject prefabs that are off-camera in the scene” -
in this public list which is exposed in the editor - the reference you set to the Game Object Prefab: are these the objects in the scene or objects (prefabs) from the Project window / prefab folder?
You should drag the actual prefab (not the instance in the scene) to the list.
Try checking this out.
Also this part:
Instantiate(EnviromentObjects[randomListObject], EnviromentObjects[randomListObject].GetComponent, Quaternion.identity)
You should pass a Vector3 here, and you pass a script it seems, since GetComponent returns a script.
Hello. I changed the list to hold the objects as prefabs in the prefab folder. I even made the start points into prefabs. Currently, each prefab has a script where i can assign a public GameObject Prefab Spawnpoint that looks like this:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class StaticEnviromentObject : MonoBehaviour
{
public GameObject spawnPointGameObject;
public Vector3 spawnPointVector3;
void Start()
{
spawnPointVector3 = spawnPointGameObject.transform.position;
}
}
Each Prefab has a spawnPoint with a Vector3 at the start (when its instantiated), so why can’t my previous script access it? Please let me know if how I phrased it does not make sense.