[Help] How to destroy a gameobject from a diffrent gameobject

Hey all! so I have this problem and I have searched all over the web for this so I don’t even know if its possible. So basicly I’m trying to Destroy a gameobject from a different gameobject via script. Ill show you the fraction of my code it I’m talking about

public GameObject CrystalForPlaceG;
void Update()
    {
        if (canDestroy == 1)
        {
            if (Input.GetButtonDown("Destroy"))
            {
                Inventory.text = "Crystal";
                //BuildingCrystal.SetActive(false);
                //CrystalForPlaceG.SetActive(false);
                //Object.Destroy(CrystalForPlaceG);
                CanPlace = 1;
                canDestroy = 0;
            }
        }

Ignore the fact that it looks like there are parts missing this is like a tiny fraction of my code and I have a ton more variables. Anyways what I’m trying to get to happen is that when you Destroy a block it Destroys the gameobject. but the problem here is I’m doing it from another script so when I play it says deleting unity assets is not permitted due to data loss. as you can see I tried multiple methods and none worked. for the set active it wouldent set the gameobject to false and then when I place another crystal it sets it false even though when I am pressing the place key (this is also in update) it sets it active but for some reason its overriding it I guess. If anyone could help that would be great. Thanks!

Is your CrystalForPlaceG a GameObject on scene or a reference of something in your project?

This error usually means that you are trying to destroy a prefab from your project folder and that is not permitted.

You could have the object(s) you are trying to destroy subscribe to an event managed by the script destroying the remote game object. This code hasn’t been tested.

//
// Destroyer Script
//
public Eventhandler<EventArgs> DestroyObject;

private void OnDestroyObject()
{
    if (DestroyObject != null)
    {
        DestroyObject(this, EventArgs.Empty);
    }
}
//
// Object to destroy script
//

[SerializeField]
private Destroyer _destroyer;

private void OnEnable()
{
    _destroyer.DestroyObject += OnDestroyObject;
}

private void OnDisable()
{
    _destroyer.DestroyObject -= OnDestroyObject;
}

private void OnDestroyObject(object sender, EventArgs e)
{
    Destroy(gameObject);
}

It’s a prefab but it’s also in my scene

Then that’s your issue. You are trying to destroy the prefab reference instead of the instantiated GameObject. You need to call the destroy and pass the instantiated GameObject reference, not the prefab one.

1 Like