[HELP] Setting the parent of a transform which resides in a prefab is disabled
Hi!
Im trying to instantiate a prefab from an array as a game object as a child of EnemySpawner GameObject.
The weird thing is, the first enemy spawns properly and is properly placed as a child. But the following one spawns not as a child and I get the error "Setting the parent of a transform which resides in a prefab is disabled"
using UnityEngine;
using System.Collections;
public class EnemySpawner : MonoBehaviour {
public GameObject[] enemies;
public GameObject enemy;
void Start(){
Spawn();
}
public void Spawn(){
Debug.Log ("Spawning new enemy!");
enemy = Instantiate (enemies[Random.Range(0,4)],transform.position,Quaternion.identity) as GameObject;
enemy.transform.parent = transform;
}
}
And here is my enemy script if you need it.
using UnityEngine;
using System.Collections;
public class EnemyBehaviour : MonoBehaviour {
public EnemySpawner spawnScript;
public float health;
public GameObject[] enemy;
void OnTriggerEnter2D(Collider2D collider){
Projectile bullet = collider.gameObject.GetComponent<Projectile>();
if(bullet){
health -= bullet.GetDamage();
bullet.Hit();
if (health <= 0){
Destroy(gameObject);
spawnScript.Spawn();
Debug.Log ("Enemy Destroyed");
}
}
}
}
What am I missing to put the following prefabs into the right parent?
That error means you're attempting to change the actual prefab. It's easy to get confused. When you use Instantiate to create something from a prefab, the new item is NOT a prefab. It's just a regular gameObject. So when the error says prefab, it means the original. There's never a problem changing the parent of a real object.
Answer by Glurth · Feb 17, 2018 at 09:52 PM
The error is indeed odd- you clearly just Instantiated the object. Perhaps you need to "disconnect" it with PrefabUtility.DisconnectPrefabInstance
. But that would be odd too, particularly as that's editor only stuff.
A possible workaround; use the last listed version of Instantiate, that takes the new object's parent, as the last parameter:
public static Object Instantiate(Object original, Vector3 position, Quaternion rotation, Transform parent);
Your answer
Follow this Question
Related Questions
Unity Addressable for player skins 0 Answers
My gameobjects keep changing layers 1 Answer
How to change value of another gameobject through script 2 Answers
How to change a game objects tag after it has been randomly selected? 0 Answers
Roll a ball and quiz (Pause scene, load scene and resume) 0 Answers