- Home /
Instantiate as a child properly
So I found need to Instantiate a prefab as a child of object, but i'm not sure how it is done and I am always getting an error:
NullReferenceException: Object reference not set to an instance of an object Player_Statistics.Update () (at Assets/Scripts/Player_Statistics.cs:23)
Evolved form of Base_Player is created, but it is not a child of "Player". The script I have:
using UnityEngine;
using System.Collections;
public class Player_Statistics : MonoBehaviour {
public static int evolution_points;
public int level;
public Rigidbody2D evolution;
// Use this for initialization
void Start () {
evolution_points = 0;
level = 0;
}
void Update (){
if (evolution_points >= 5) {
evolution_points = 0;
Debug.Log ("Level up!");
foreach (Transform child in transform) {
GameObject.Destroy (child.gameObject);//destroy all childs
//creates evolved form of player at the same hierarhy possition
Transform evolved_player = Instantiate(evolution, child.position, child.rotation) as Transform;
evolved_player.parent = gameObject.transform;
return;
}
}
}
}
Before playing game I have:
Please do not hesitate to give any tips, thanks in advance.
Answer by steakpinball · Apr 24, 2015 at 07:39 PM
There are a couple issues. Prefab references should be of type GameObject
. Change the evolution
field to that
public GameObject evolution;
You need to then cast it to GameObject
when you instantiate it.
GameObject evolved_player = Instantiate(evolution, child.position, child.rotation) as GameObject;
evolved_player.transform.parent = transform;
Your answer
![](https://koobas.hobune.stream/wayback/20220613193933im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
AddForce not working on Instantiated Object 0 Answers
Instantiate script for randomly selecting sound is suddenly creating New Game Object in hierarcy?? 2 Answers
[4.6] Instantiating an object within a ScrollView makes the object invisible 0 Answers
Equivelant "set" method for "getInstantiatedObject"? 0 Answers