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\$
8
  • \$\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\$ Commented Jun 22, 2014 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\$ Commented Jun 22, 2014 at 21:10
  • \$\begingroup\$ that really doesn't make sense, there must be something else. \$\endgroup\$ Commented Jun 22, 2014 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\$ Commented Jun 22, 2014 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\$ Commented Jun 22, 2014 at 21:29

1 Answer 1

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\$
1
  • \$\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\$ Commented Dec 23, 2014 at 15:10

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.