- Home /
Prefab as child of existing GameObject
I've seen this asked 50 times and the common answer isn't working for me. Any ideas? here is my code, i want to create a prefab as a child of the current object
using UnityEngine;
using System.Collections;
public class Scheduler : MonoBehaviour {
public Transform X;
void Start () {
}
void OnMouseDown (){
switch (this.name){
case "d113":
GameObject test = Instantiate(X, new Vector3 (0,0,0), Quaternion.identity) as GameObject;
test.transform.parent = transform;
break;
}
}
}
And I always get this error against the second line: NullReferenceException: Object reference not set to an instance of an object
Seems pretty simple, I'm not sure what I could be missing. If i take out the second line, it works find and the prefab is created without a parent.
Thanks!
That should work. Something else may be going wrong, not sure what though. However the quaternion should be with a capital Q.
Yup, Same effect.
I also tried changing the second line to add a regular GameObject and it works.
Updating to include entire script...
Answer by RayJr · Feb 02, 2015 at 01:53 AM
Oops, nevermind. Was declaring it as a Transform in line 5. I must have combined solutions and screw it all up. Thanks !
Answer by Simon-Larsen · Feb 02, 2015 at 01:59 AM
Your problem is that X is a Transform, but you're trying to cast it to a GameObject, however, Tranform doesn't inherit from GameObject so that won't work. You could either cast your instantiation result to a Transform or you could change your X variable type to GameObject.
So, either
Transformm test = Instantiate(X, new Vector3 (0,0,0), Quaternion.identity) as Transformm;
test.parent = transform;
or
public GameObject X;
Remember to reassign your prefab to your script if you're changing the type.