I have a string that has a prefab name, I want to instantiate a prefab with that name in the prefabs folder. Does anyone know how to do this?
Thanks in advance.
CodePudding user response:
If it is necessary to instantiate a prefab by its name, you can put said prefab into the Resource folder and use Resources.Load
method:
// Instantiates a Prefab named "prefabName" located in any Resources folder in your project's Assets folder.
GameObject instance = Instantiate(Resources.Load("prefabName", typeof(GameObject))) as GameObject;
Unity Manual on Resources.Load
Otherwise you can use SerializeField and choose the required prefab in the inspector
// Reference to the Prefab. Drag a Prefab into this field in the Inspector.
[SerializeField] private GameObject myPrefab;
// This script will simply instantiate the Prefab when the game starts.
void Start()
{
// Instantiate at position (0, 0, 0) and zero rotation.
Instantiate(myPrefab, new Vector3(0, 0, 0), Quaternion.identity);
}