Destroy button only destroys the last clone of object
Hello, I am working on a 2d isometric grid building system, and I have encountered a problem with destroying already placed objects. So I have a prefab with a panel and buttons, one button for placement and the other for destroying the prefab clones. It works but only for the prefab clone that was placed last. If I try to destroy others I get this error "MissingReferenceException: The object of type 'Building' has been destroyed but you are still trying to access it.".
Here is the code I use to instantiate objects
public void InstantiateObject(GameObject gameObject)
{
if(!objectUnplaced)
{
if (canBePlaced)
{
current=Instantiate(gameObject,Vector3.zero,Quaternion.identity).GetComponent<Building();
GridBuildingSystem.instance.FollowBuilding(current);
towerUnplaced = true;
}
}
}
This method is called from buttons script:
public void DestroyObject()
{
Destroy(gameObject);
}
I understand what the error means but I don't really know how to solve it, does anybody have any suggestions on how to fix it?
Answer by Dsiak · Nov 21, 2021 at 08:26 AM
You shouldn't use "gameObject" as a parameter name because "gameObject" is the Game Object the script is attached to, which also means your DestroyObject function is probably only deleting the Game Object the script is attached to. Maybe this is creating the problem
Try using a different name and see if it helps
Thank you, but it still doesn't work. I should have worded this question better and also describe my issue properly, here is a video I recorded that shows what I need to do: video
Do you know how can I fix this? Sorry for bothering you.
Sorry if I'm not any help I ant a master programmer.
It looks like you have a very solid system already, can you try to following see if it works? Maybe a variable of type Building called "currentlySelectedBuilding" is set every time you click one of the buildings and then "DestroyObject" destroys the "currentlySelectedBuilding.gameObject"
It doesn't work but now looking at my code my Building current is public static? Can this be the reason why it doesn't work?
Edit: So, I was playing around and turned off the buttons and added if statement for destroying with ESC in my dragging function, and instead of Destroy(gameObject or current.gameObject) I used transform.gameObject, and it kinda works but only if I don't place the object and I still get the error once I delete an object that was instantiated last but it continues to work, so it seems that there is a problem with public static Building. What do you think?