- Home /
instantiate prefab object to existing object
Hi,
I am trying to instantiate a prefab object, which is a simple Gameobject with a plane (including mesh renderer, mesh filter ofcourse) to the position of an already existing gameobject in the scene. The prefab object to Instantiate doesn't exist in the scene yet, and I have trouble letting unity know which object to instantiate.
It gives me the error: NullReferenceException UnityEngine.Object.Internal_InstantiateSingle (UnityEngine.Object data, Vector3 pos, Quaternion rot) (at C:/BuildAgent/work/cac08d8a5e25d4cb/Runtime/ExportGenerated/Editor/UnityEngineObject.cs:72) UnityEngine.Object.Instantiate (UnityEngine.Object original, Vector3 position, Quaternion rotation) (at C:/BuildAgent/work/cac08d8a5e25d4cb/Runtime/ExportGenerated/Editor/UnityEngineObject.cs:82)
Now I know that a NullReferenceException basically means that Unity can't find the object I want to Instantiate.
Here is my code: ( I tried many variations of this)
var GraphicNew : GameObject;
var Graphic : GameObject;
Graphic = GameObject.Find("/Graphic"); //the prefab object to instantiate which doesn't exist in the scene, but is in the project files.
function Start () {
//attach graphic object to the object of this script
GraphicNew = Instantiate(Graphic, transform.position, transform.rotation);
GraphicNew.transform.parent = gameObject.transform; //attaches to object
}
Am I missing something? Any help would be appreciated.
Answer by cdrandin · Aug 04, 2013 at 11:37 PM
GameObject.Find, if you read carefully in the docs (http://docs.unity3d.com/Documentation/ScriptReference/GameObject.Find.html) Finds the game object with the name attached to it. Most likely your object is not called "/Graphic". It seems you are trying to access a folder and instantiate an object from the folder which can't be done this way, or maybe at all, but doubt.
Also, put GameObject.Find in the Start() function, it may actually just work, but if that doesn't then either put the appropriate name or drag and drop using the inspector.
Well, I could not get GameObject.Find to work. Your last suggestion however did the trick: I just drag and dropped the correct gameobject to the inspector view to the slot of the Graphic variable. Thanks :)
Your answer
Follow this Question
Related Questions
initial velocity for instantiated ragdoll prefab 1 Answer
NullReferenceException from a script after linking prefab with drag and drop in inspector. WTF? 1 Answer
Referencing gameObject from script after Instantiate 0 Answers
Object reference to set to instance on an instantiated object 1 Answer
NullReferenceException: Object reference not set to an instance of an object 1 Answer