I am trying to instantiate a random prefab from an array at a the position of an existing gameobject and parent it to that gameobject. The problem is I get this error “Cannot implicitly convert type UnityEngine.Object' to UnityEngine.GameObject’. An explicit conversion exists (are you missing a cast?)” But it all seems like it should work, I have probably searched every possible similar question with no results so I came here.
Code:
GameObject[ ] prefab;
Vector3 coords;
int index;
GameObject randomPrefab;
string parentName;
//gets all prefabs in the “prefabFolder” and adds them to an array of GameObjects.
void start()
{
prefab = Resources.LoadAll(“prefabFolder”) as GameObject[ ];
populateScean();
}
//gets a random prefab from the array.
public void getRandomPrefab()
{
index = Random.Range (0, prefab.Length);
randomPrefab = prefab[index];
}
//populates the whole scean by populating each area (area is a terrain GameObject).
public void populateScean()
{
getRandomPrefab();
parentName = “name1”;
coords = GameObject.Find(parentName).transform.position;
populateArea(randomPrefab, coords);
getRandomPrefab();
parentName = “name2”;
coords = GameObject.Find(parentName).transform.position;
populateArea(randomPrefab, coords);
//I do this a total of 8 times because I have 8 terrain gameObjects (areas I called them in this example) they act similarly to chunks.
}
//parents the random prefab at the coords of the area.
public void populateArea(GameObject randomPrefab, Vector3 coords)
{
GameObject rPrefab = Instantiate (randomPrefab, coords, Quaternion.identity);
rPrefab.transform.parent = gameObject.transform;
}