- Home /
Instantiate prefab as child - Won't work, don't know why.
I've done this before, I even tore code out of a previous project that I know to work, but for some reason, it does not.. I get:
NullReferenceException: Object reference not set to an instance of an object
Regardless of what I've tried.
void Update ()
{
if (Input.GetKey (KeyCode.Mouse1) && Time.time > fireRate)
{
fireRate = Time.time + 1.5f;
Rigidbody2D bladeClone;
bladeClone = Instantiate(blade, transform.position, transform.rotation) as Rigidbody2D;
bladeClone.transform.parent = transform;
}
}
}
I have no idea why it doesn't work in one of the multiple iterations i've tried.
I've stored the transform as a variable in both the object to which the script is attached AND in much more complicated fashion; through a script on the object that is being instantiated itself, among other things.
No variation works, neither GameObject.Find, Storing the transform as a local or even global variable.
If I press Mouse1 and pause after the object appears and MANUALLY parent it to the object in question, nothing bad happens, and I get the exact result I would've expected the code to produce.
I'm at a loss. Code that used to work in previous projects has also broken for seemingly no reason.
I've been beating my head against this for hours now.
What am I missing here?
Answer by Luk3ling · Apr 13, 2015 at 02:03 AM
I eventually tried a new approach via tagging and searching from the instantiated object by attaching the following script to the prefab:
using UnityEngine;
using System.Collections;
public class basicBldTest : MonoBehaviour {
Transform parent;
void Start () {
parent = GameObject.FindGameObjectWithTag ("MeleePivot").transform;
this.gameObject.transform.parent = parent;
}
}
I shouldn't have to have done this, however, so the whole thing still irks me.
Your answer
![](https://koobas.hobune.stream/wayback/20220613192952im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How do I get the global position 2 Answers
Check if child exists and instantiate as child 1 Answer
Instantiate the subchild (the renderer) from prefab? 1 Answer
Prefab - Child of GameObject. 0 Answers
prefab question 1 Answer