0
\$\begingroup\$

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?

\$\endgroup\$
  • \$\begingroup\$ 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? \$\endgroup\$ – Roberto Jun 22 '14 at 20:42
  • \$\begingroup\$ 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. \$\endgroup\$ – Morphex Jun 22 '14 at 21:10
  • \$\begingroup\$ that really doesn't make sense, there must be something else. \$\endgroup\$ – Roberto Jun 22 '14 at 21:15
  • \$\begingroup\$ 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? \$\endgroup\$ – Morphex Jun 22 '14 at 21:18
  • \$\begingroup\$ 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. \$\endgroup\$ – Roberto Jun 22 '14 at 21:29
1
\$\begingroup\$
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;
\$\endgroup\$
  • \$\begingroup\$ 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. \$\endgroup\$ – Morphex Dec 23 '14 at 15:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.