Instantiating an object based on the name of another object?

I am making an inventory system. Whenever you pick something up, the GameObject is destroyed and an empty GameObject is created inside the player’s inventory. What I am trying to do is the following:

When you press “E” I want to instantiate the prefab with the same name as the object in the inventory,
but when I try that I get an error because I cannot instantiate an object using a string. Any fixes?
Here is my code:

private int next = 0;
void Update()
{
if (Input.GetKeyDown(KeyCode.E))
{
GameObject nextOb = Inventory.transform.GetChild(next).gameObject;
Instantiate();
Destroy(nextOb, 0f);
next++;
}
next = 0;
}

It is always more helpful to supply formatted code like so:

private int next = 0; 

void Update()
{ 
    if (Input.GetKeyDown(KeyCode.E))
    {
        GameObject nextOb = Inventory.transform.GetChild(next).gameObject;
        Instantiate(); 
        Destroy(nextOb, 0f);
        next++;
    } 
    next = 0;
}

Anyhow, you are not instantiating anything at all here and next is changed to 1 and then changed back to 0 right afterwards so GetChild() will always return the first child of the transform.


You need to supply the game object/prefab that you want to create like this “Instantiate(prefabReference);” , afterwards you can give it any name you want. GameObject.name can be used for supplying or getting a name of the object.