C# - Cannot destroy instantiated object

Hi! I am having a problem in C#. I am able to instantiate a prefab on mouse over, but when I try to destroy on mouse exit, it doesn’t do anything. I found a lot of solutions online and none worked.
If I move the Destroy line into the OnMouseEnter method, it destroys it just fine after one second, but nothing happens when I leave it on mouse exit. It looks as if OnMouseEnter is not passing variables to OnMouseExit. Shouldn’t the opposite happen since both myPrefab and clone are public?
Any help would be greatly appreciated.

Here’s my code:

public class Button : MonoBehaviour {

public GameObject myPrefab;
public GameObject clone;

void OnMouseEnter()
{
var clone = Instantiate(myPrefab, gameObject.transform);
}

void OnMouseExit()
{
Destroy(clone.gameObject, 1f);
}

}

Thank you in advance!!!

You are creating a local variable with the same name. Remove var from Instantiate code.

public class Button : MonoBehaviour
{

    public GameObject myPrefab;
    private GameObject clone;


    void OnMouseEnter()
    {
        clone = Instantiate(myPrefab, gameObject.transform);
    }

    void OnMouseExit()
    {
        if (clone != null)
        {
            Destroy(clone.gameObject, 1f);
        }
    }


}
2 Likes

Thank you so much, @WarmedxMints_1 !!! It works now!