Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Trying to load a prefab via C# script

Discussion in 'Editor & General Support' started by CasperJames, Sep 25, 2013.

  1. CasperJames

    CasperJames

    Joined:
    Jul 11, 2013
    Posts:
    1
    Okay - so here's the situation: I have a spider model as an FBX that loads fine - I also made a prefab inside unity (added colliders and other stuff to it) and exported it and have the prefab file.

    Let's call the prefab new_spider and let's call the FBX just spider.

    Enter Code:

    Code (csharp):
    1.             _main = GameObject.Find("Startup").GetComponent<Main>();
    2.             GameObject spider = (GameObject)Resources.Load("npc/fantasySpider/spider_new");
    3.             //Debug.Log("Calling spider");            
    4.             spider.name = "Spider!";            
    5.             Instantiate(spider, new Vector3(8216, 600, 8216), Quaternion.identity);    
    Again the FBX loads fine with the above code but my prefab will not - I keep getting cast error

    InvalidCastException: Cannot cast from source type to destination type.
    GameEngine.Character.NPC.Start ()

    I have googled and googled and cannot seem to load the prefab - any help is greatly appreciated! I have read about Transform and couldn't get that to work either.

    Edit: I know that it is erroring out on this line: GameObject spider = (GameObject)Resources.Load("npc/fantasySpider/spider_new");
     
  2. foxter888

    foxter888

    Joined:
    May 3, 2010
    Posts:
    530
    it doesn't seems to like the way you are casting, sometimes you have to cast it different so instead of saying:
    (GameObject)Resources.Load("npc/fantasySpider/spider_new");

    you should try instead: Resources.Load("npc/fantasySpider/spider_new") as GameObject;