0

I have two cs files, Main.cs and Menu.cs. On OnGUI event which is in Main.cs file I call method from Menu.cs.

private void OnGUI()
{
    Menu menu=new Menu();
    menu.Create_Menu();
}

And in Menu.cs.

public void Create_Menu ()
{
    StartCoroutine(LoadCar());
}
private IEnumerator LoadCar()
{
    //Load Object
    Download    download;
    download=new Download();
    GameObject go = null;
    yield return StartCoroutine(LoadAsset("http://aleko-pc/3dobjects?key=1017&objecttype=1","car13",(x)=>{go = x;}));
}

I get error NullReferenceException UnityEngine.MonoBehaviour.StartCoroutine (IEnumerator routine)

If I copy private IEnumerator LoadCar() method in Main.cs class, and call from OnGUI it works.

Maybe I do not understant working area of Coroutines, Can any body help me?

GrandMasterFlush
  • 6,269
  • 19
  • 81
  • 104
tungi
  • 15
  • 1
  • 8
  • possible duplicate of [What is a NullReferenceException and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – CodeSmile Feb 16 '15 at 10:51

1 Answers1

0

First of all the OnGUI method is called every frame and I don't think you want to download the assets every frame.

Second, you need to make sure Menu is derived from MonoBehviour and added to the view hierarchy.

A better approach would be to add Menu as a component to a GameObject (maybe the same that has the Main script attached) and call Create_Menu on the Start method of Menu.

Radu Diță
  • 13,476
  • 2
  • 30
  • 34
  • Thanks for reply, i'll answer your questions. First, script which i show is part of my project, actually I download asset on click to my menu button.Second, Menu class is derived from MonoBehavior and is attached on GameObject. Third, my menu is combined from buttons so it need to be redraw in new frame thats why it is in OnGUI. – tungi Apr 08 '14 at 21:21