- Home /
How to Instatiate a prefab using an absolute path
Hello guys, I have a counter object that persists between the scenes, to save things like score and number of lives. But when I want just to test the game level, I must run the level before just to get this object, so I thought to do something like.
counter = GameObject.Find( "Counter" );
if ( counter == null )
{
counter = GameObject.Instantiate( Resources.Load("Assets/GameManager/Prefabs/Counter.prefab", GameObject ) );
if ( counter == null )
{
Debug.Log( "StageGUI can't find the Counter object ");
}
}
But the Instantiate part doesn`t work. Anyone knows how to do something like this? Also is normal to Unity crash down when you try to call a method from a null gameObject? Thanks
Answer by asafsitner · Feb 23, 2012 at 01:47 PM
As seen on the `Resources.Load` page, file extensions must be omitted. Try it without the ".prefab" at the end.
Hmmm but according to the documentations, the files must be in a folder called "Resources", isn't it?
Yes. But the absolute path must exclude the file extension.
Answer by PGilmore · Mar 14, 2013 at 11:20 PM
For example, this code: Resources.Load("TestFolder/TestAsset", typeof(GameObject));
Will load a prefab called "TestAsset" in the "./Assets/Resources/TestFolder/" directory. The object returned will be of type GameObject.