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…
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?