In my scene - I have created a ui button on a panel. I have attached my cube prefab on this button and have also written a script to instantiate the prefab.
The problem I have is when I click on the button the cube appears. But if I click on it again it does not appear. I want the cube to appear each time I click on the button. Can any one help me with this? I am new to unity will be great if I could get some help.
,
you need to add a new method, and change the setactive method from the button to this one public void InstantiateGameObject(GameObject _object) { Instantiate(Resources.Load("mycubePrefab")); }
1 - Create a MonoBehavior script that you will attach to your button
2 - Create an Instanciate(prefab) methods that will be called from the OnClick UnityEvent, something like this:
public class Instantiator : MonoBehaviour
{
public void InstantiateCaller(GameObject prefab)
{
Instantiate(prefab);
}
}
3 - From your button, call this method instead of GameObject.SetActive and drag and drop your prefab from the Project folder and not from the scene in the argument part.
Also, remove the prefab you already have in your scene, it’s misleading
I’d also be careful what the transform is for instantiated objects. If the transform/position isn’t changing, you could just be creating objects on top on one another so it just appears they aren’t being created. Easiest way to check to see if an object was instantiated is to check the hierarchy when game is running.
Hello! I am working in unity 3d with oculus quest. I want to click a button and load a prefab(which I got). I want to click the button again and another copy of prefab must be loaded.
you need to add a new method, and change the setactive method from the button to this one public void InstantiateGameObject(GameObject _object) { Instantiate(Resources.Load("mycubePrefab")); }
– xxmariofer