- Home /
Destroying Assests Not Permitted
public class birdScript : MonoBehaviour
{
private GameObject bird;
// Update is called once per frame
void Update()
{
if(gameObject.transform.position.y < -20)
{
Destroy(gameObject);
}
}
public void hitCheck(float playerx, float playery)
{
if(playerx - 2 < gameObject.transform.position.x && playerx + 2 > gameObject.transform.position.x)
{
if (playery - 2 < gameObject.transform.position.y && playery + 2 > gameObject.transform.position.y)
{
DestroyBird();
}
}
}
void DestroyBird()
{
Debug.Log("die");
bird = gameObject;
Destroy(bird);
}
}
So basically I have a birdPrefab and on that prefab I have a bird script. In the script I want to destroy the bird if hitcheck is called, but it says that it is not permitted. I have tried to look for this in other places but none of them had answers specific for destroying the gameObject.
I know this isn't what you asked but I would suggest looking up spawn-pooling.
Deallocating memory during your games running can cause dips in performance as the GC kicks in. So if you can avoid using calls that do any deallocation outside of lifecycle methods that happen at the loading intervals. It will do you a bunch of favours when you come to want to optimise later on.
Answer by medinaline · Jan 26, 2020 at 05:25 AM
From my understanding, Unity shows that message when the code would delete the actual asset in the project, rather than destroying the instance of the gameobject. Do you get the same error when calling Destroy(gameObject) rather than the assigned private variable bird, like you do in Update()?
Yes, I get the same error, when i do Destroy(gameObject).
When and how does hitCheck get called? It looks like you're calling it on the prefab, which means it ends up trying to destroy the prefab. medinaline is correct: you can't do that.
You need to call it on the scene object ins$$anonymous$$d, the thing you instantiated from the prefab.
Sorry, I was away all day yesterday.
I think it may have to do with how the bird object is being instantiated. It's really just a guess at this point. Good luck!
Your answer
Follow this Question
Related Questions
using Contains(gameObject) to find and destroy a gameObject from a list 2 Answers
Optimize huge number of Destroy() calls (cannot use object pooling) 3 Answers
Destorying gameobjects on a network 0 Answers
Can you destroy an object using GetInstanceID? 0 Answers
Why are my Game Objects being destroyed? 0 Answers