0
\$\begingroup\$

I want my gameObject named lvl_01 to destroy when I click left or right arrow key but it's keep showing this error "Destroying assets is not permitted to avoid data loss" instead of destroying that gameObject, Can anybody please tell me what is going wrong around here.

using UnityEngine;
using System.Collections;

public class Level_01Text : MonoBehaviour {
public GameObject lvl_01;
// Use this for initialization
void Start () {
    Instantiate (lvl_01);
}

// Update is called once per frame
void Update () {
    if((Input.GetKey(KeyCode.RightArrow)) || (Input.GetKey(KeyCode.LeftArrow)))
    {
        Destroy (lvl_01);
        Debug.Log ("Something is seriously going wrong around here");
    }
}

}
\$\endgroup\$
1
  • \$\begingroup\$ You can't destroy memory in a managed language anyway. The most Unity can do is set it to null, remove it from render queues, and hope the garbage collector grabs it in a timely fashion. \$\endgroup\$
    – Krythic
    Commented Nov 27, 2016 at 2:44

1 Answer 1

2
\$\begingroup\$

You're trying to destroy the prefab, which Unity does not allow.

In Start function you instantiated the GameObject (a Prefab) which was assigned in inspector. Therefore, the instantiated GameObject "lvl_01" contains reference to Original Prefab, destroying which will also destroy the Prefab.

What you should do is define an empty GameObject (let's call it temp) and give it the reference to your instantiated prefab and Destroy as required.

using UnityEngine;
using System.Collections;

public class Level_01Text : MonoBehaviour {
public GameObject lvl_01;
GameObject temp;

// Use this for initialization
void Start () {
    temp = Instantiate (lvl_01);
}

// Update is called once per frame
void Update () {
    if((Input.GetKey(KeyCode.RightArrow)) || (Input.GetKey(KeyCode.LeftArrow)))
    {
        Destroy (temp);
        Debug.Log ("Something is seriously going wrong around here");
    }
}

}
\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .