- Home /
Resource.Load Prefab not working on a fetched string
I am trying to instantiate a prefab with Resource.Load as its parameter but it gives "ArgumentException: The thing you want to instantiate is null."
I saw almost all questions on this topic but in my case i feel the problem is a bit different.
I have 3 prefabs named Tree101, Tree102, and Tree103 namely in my Resources folder which is in my assets folder.
My Instantiate code is: GameObject treePut = (GameObject)Instantiate(Resources.Load(treeToPut,typeof(GameObject)));
I also tried : GameObject treePut = (GameObject)Instantiate(Resources.Load(treeToPut));
where treeToPut is string variable which gets input from a text file. I used Debug.Log to check if it returning right string name and it does give either Tree101,Tree102 or Tree103.
Now I checked treeToPut = "Tree101"
and my code works without error.
My treeToPut code is:`
string treeToPut = pickTree();
public string pickTree()
{
string treeName;
if (leveldata.dataLoaded)
{
int totalTrees = leveldata.treePosDB.Length;
int pickedTree = Random.Range(1, totalTrees);
treeName = leveldata.treePosDB[pickedTree].treeName;
}
else
{
treeName = pickTree();
}
return treeName;
}
` Debug.Log gives the same values as the prefab names so i dont know what im doing wrong, please if anyone can solve my doubt...
Answer by socialspiel · Apr 25, 2014 at 01:52 PM
First i would recommend to split the calls up. The compiler will create temporary variables anyway.
Debug.Log(treeToPut);
GameObject prefab = Resources.Load(treeToPut) as GameObject;
Debug.Log(prefab);
GameObject treePut = Instantiate( prefab ) as GameObject;
Debug.Log(treePut);
You will most likely see that the prefab is null as the error message says. Make sure that it isn't in a subfolder or that the subfolder is in the name (eg. "trees/tree101")
When you set the treeToPut to "tree101" and it works, then maybe you got control characters in the tree names from parsing the text file?
Can you explain a bit about the control characters because i think that too to be my problem but dont know where to search for it.
and regarding splitting up the commands i already tried that... doesnt work...
edit: prefab returns null but ot is in the Resources folder at root level so that is not the problem, the string being passed looks same as the prefab name in Debug.Log
i tried using Encoding.Convert to convert from UTF8(text file encoding is in UTF8) to Unicode but that doesnt work either
string tempTreeName = lines[mi++].Trim();
I put this where my script reads data from file, worked like a charm thanks for you help!!
Your answer
