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

fixed the link, thanks

2 Answers

2

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.

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.