Want to instantiate Prefab in its parent.
Hello, I am using a code to spawn randomly gameobjects in a scrolling game. The instantiating works great but I want the cloned gameobjects to be children of the gameobject carrying the script instead of creating themselves at the root of the editor, this is because of parallax issues my game is based on. I tried a code but I have this error : Setting the parent of a transform which resides in a prefab is disabled to prevent data corruption. UnityEngine.Transform:set_parent(Transform) spawn:SpawnEnemy() (at Assets/Scripts/SpecialScripts/spawn.cs:44) spawn:Update() (at Assets/Scripts/SpecialScripts/spawn.cs:31)
This is the code, I am not the author just using it.:
using UnityEngine; using System.Collections;
public class spawn : MonoBehaviour {
// Use this for initialization
public GameObject[] enemyPrefabs;
public float numEnemies;
public float xMin = 19F;
public float xMax = 85F;
public float yMin = 3.5F;
public float yMax = -4.5F;
public float spawnCooldown = 1;
private float timeUntilSpawn = 0;
void Start()
{}
// Update is called once per frame
void Update()
{
timeUntilSpawn -= Time.deltaTime;
if(timeUntilSpawn <= 0)
{
// Do your enemy spawns here
for (int i = 0; i < numEnemies; i++)
{
SpawnEnemy();
Destroy(gameObject, 20);
}
// Reset for next spawn
timeUntilSpawn = spawnCooldown;
}
}
private void SpawnEnemy()
{
GameObject enemyPrefab = enemyPrefabs[Random.Range(0, enemyPrefabs.Length)];
Vector3 newPos = new Vector3(Random.Range(xMin, xMax), Random.Range(yMin, yMax), 0);
GameObject octo = Instantiate(enemyPrefab, newPos, Quaternion.identity) as GameObject;
enemyPrefab.transform.parent = GameObject.FindGameObjectWithTag("EnnemySpawn").transform;
}
}
Answer by tinglers · Mar 07, 2017 at 08:44 AM
In the instantiate function there's an overloaded parameter for Transform parent.