# Unity3D : Prefab Instancing Issue

I am using latest unity engine and I am having a scripting issue.

I create a prefab , added a few scripts to it and I am trying to instantiate a few of those objects like this :

        GameObject go = Instantiate(Prefab) as GameObject;
var co = go.GetComponent<MyScriptA>();


Issue here is co is always null, this means that MyScriptA is no on the go instance. Accessing the prefab.GetComponent also returns null, but the prefab has the scripts in the editor and its assigned also in the editor to the Prefab variable (drag dropping). So I am not sure what might be wrong. For example if I Debug.Log(prefab) its not null.

So what am I doing wrong here?

• ok, so if you delete everything in the Hierarchy pane and then drag and drop the prefab from the Project pane to the Hierarchy pane, will it have the scripts? – Roberto Jun 22 '14 at 20:42
• It does. All the scripts are there, I even tried creating a prefab with only a particle system (maybe it was a issue on my script) Still the same applys. – Morphex Jun 22 '14 at 21:10
• that really doesn't make sense, there must be something else. – Roberto Jun 22 '14 at 21:15
• I have been looking everywhere, maybe I did my prefab wrong. I just create a object added my script to it, created a prefab dragged the object on top of it, then tried to execute that code, and it says that its always null. Does anything I said seems like the wrong way to do it? – Morphex Jun 22 '14 at 21:18
• no, that's it... and if you dragged into the Hierarchy and you saw in the inspector what you wanted, then it's correct. It must be something in your loading code. – Roberto Jun 22 '14 at 21:29

GameObject go = Instantiate(Prefab) as GameObject;


Since go is a gameobject your prefab must also be a gameobject Make sure you have something like

GameObject prefab;


at the start rather than

Transform prefab;

• Honestly I am not sure What was the issue, but somehow I fixed when I reinstalled Unity + Rewrote most scripts. So I am accepting this as answer because this is actually he correct way. – Morphex Dec 23 '14 at 15:10