Destroy a prefab from another class
I'm simply trying to destroy a prefab from another class using a button. However my code does not work properly.
Here is the Class that makes the prefab.
public class MapGrid : MonoBehaviour {
//Transform object
public GameObject gridObject;
void Start(){
generateGrid ();
}
public void generateGrid(){
gridObject = Instantiate (gridObject);
}
}
Here is the Class that is supposed to destroy the prefab.
public class DecreaseSize : MonoBehaviour {
//allows access to public mapgrid fuctions
MapGrid mg = new MapGrid();
public void decreaseMapSize(){
Destroy (Instantiate(mg.gridObject));
}
}
Not sure what I am doing wrong. But it is probably pretty simple.
Answer by Chiroculon · Apr 06, 2017 at 12:38 PM
In decreaseMapSize your are instantiating a new GameObject by copying mg.gridObject and then immediately destroying it.
So to fix it, just remove that Instantiate, like so:
public void decreaseMapSize(){
Destroy (mg.gridObject);
}
Answer by SohailBukhari · Apr 06, 2017 at 01:07 PM
The DecreaseSize Class Object you want to instantiate is null. You need to take reference of the class DecreaseSize before instantiating.
using UnityEngine;
public class DecreaseSize : MonoBehaviour {
//allows access to public mapgrid fuctions
public MapGrid mg;
private void Start()
{
mg = FindObjectOfType<MapGrid>();
}
public void decreaseMapSize()
{
Destroy(Instantiate(mg.gridObject));
}
}
and this is not the good way of doing it. best way is to use event system for your object to destroy. Make a non-persistent Event system Class and place all events in the class as below
using UnityEngine;
using UnityEngine.Events;
public class EventSystemSingelton : MonoBehaviour {
private static EventSystemSingelton instance;
public static EventSystemSingelton Instance
{
get
{
if (instance == null)
{
instance = GameObject.FindObjectOfType<EventSystemSingelton>().GetComponent<EventSystemSingelton>();
}
return instance;
}
}
// Event For your object to destroy.
public UnityEvent ObjectDestroy;
}
Then in your class MapGrid listen for that event and destroy on invoke(). as below
using UnityEngine;
public class MapGrid : MonoBehaviour
{
public GameObject gridObject;
private void Start()
{
EventSystemSingelton.Instance.ObjectDestroy.AddListener(delegate { Destroy(gridObject); });
generateGrid();
}
public void generateGrid()
{
gridObject = Instantiate(gridObject);
}
}
Then invoke Event on your Button Click method in DecreaseSize class.
using UnityEngine;
public class DecreaseSize : MonoBehaviour {
public void decreaseMapSize()
{
EventSystemSingelton.Instance.ObjectDestroy.Invoke();
}
}