I want to destroy a prefab child object upon collision

I want to destroy the prefab "Fruit" upon collision of the sprite and the parent object "Bloom", but when i test play it, it show a error saying:

Destroying assets is not permitted to avoid data loss.
If you really want to remove an asset use DestroyImmediate (theObject, true);

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class FruitRegrowth : MonoBehaviour
{
    public GameObject Fruit;
    public GameObject Bloom;
    public bool FruitExist = true;
    void Start()
    {
        Instantiate(Fruit, transform);
    }
    void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.name == "Sprite")
        {
            Destroy(Fruit);
            FruitExist = false;
            Debug.Log(collision.gameObject.name);
        }
    }
}

1 Answer

1

This happens if Fruit points to an asset in the asset folder. Make sure the object you’re destroying points to a GameObject instance in the scene, not the asset folder.

To update your code: assign the prefab to FruitPrefab.
When you instantiate a fruit, store a reference of it to fruit
Destroy the fruit instance, not FruitPrefab

public class FruitRegrowth : MonoBehaviour
{
	public GameObject FruitPrefab; //Reference to Fruit prefab in asset folder

	public GameObject fruit; //Instantiated fruit
	public bool FruitExist = false;

	void Start ()
	{
		fruit = Instantiate (FruitPrefab, transform);
         FruitExist =true;
	}

	void OnCollisionEnter2D (Collision2D collision)
	{
		if (collision.gameObject.name == "Sprite") {
			Destroy (fruit); //Destroy fruit instance
			FruitExist = false;
            
			Debug.Log (collision.gameObject.name);
            
		}
	}
}

Thanks for the help man i appreciate ya

–