How to Instantiate and Destroy a GameObject in Unity

Updated on March 12, 2020

Creating and removing GameObjects in Unity happens all the time in just about every game, and so one of the first things a beginner programmer needs to learn is how to both Instantiate and Destroy GameObjects. The one process ties into the other, so we're going to approach this topic from the opposite end and look at Destroying a GameObject first.

Destroying a GameObject

Destroying a GameObject in Unity requires, at its most basic, only two elements:

  • A script that derives from MonoBehaviour, Unity's standard base class for virtually everything the program does; and
  • A single line of code: 'Destroy(insertGameObjectHere);'.

Assuming you have those two elements in play in a script you can destroy a GameObject. Sounds pretty easy, right? Here's a quick example:

Source

In this case you have a GameObject, stored as 'guyGameObject', and a Destroy command that triggers if you hit the F key. You also have a script derived from MonoBehaviour, as Destroy won't be recognized as a function outside of this all-important base script. This will, in theory, remove the GameObject and everything childed to it from your game when you hit F. Pretty easy.

... except, despite the code being technically correct, this won't actually work. Instead you'll get a small error in the Console at the bottom of the screen: 'Destroying assets is not permitted to prevent data loss.' What does this mean? To explain, we'll need to look at Instances.

Creating an Instance of a GameObject

Instances are clones of prefabricated GameObjects - prefabs - which form the basis of all in-game interactions in Unity. A prefab is created whenever you drag a GameObject from the Scene view into the Project view, thereby saving it in your game's Assets. The prefab can then be drawn upon via Inspector variables to create copies for runtime purposes. Think of the prefab as a blueprint for an object, and the Instances are the manufactured result of that blueprint. You don't want to use and discard the blueprint, just the manufactured results.

As a consequence of this, Unity will display the aforementioned error whenever you (accidentally) try to Destroy a prefab. If you see the error you know that you're trying to Destroy the wrong thing. So in order to fully understand how to Destroy a GameObject in Unity, you also need to understand how to Instantiate an object.

Create a new script (or use one already in progress) and add a new public GameObject variable, as above. Then go back to the Inspector and add a prefab to your script, like so:

Source

You now have a connection to the prefab blueprint in your script. Using the guyGameObject variable you can create an Instance of the prefab using this line of code:

Instantiate(guyGameObject);

When this script is run, assuming guyGameObject is assigned to a prefab, a clone of that GameObject will be created in your game, appearing at the same coordinates contained within the prefab. You can even assign new coordinates, if you like, and change where the clone of guyGameObject will appear:

Instantiate(guyGameObject, new Vector3(0, 0, 0), Quaternion.identity);

This will create a clone of guyGameObject at the global coordinates of 0, 0, and 0. You can also use the Vector3 of another object to Instantiate your clone in a movable spot by creating another variable and assigning it to an active GameObject like so:

float instX = instantiateObjectHere.transform.position.x;
float instY = instantiateObjectHere.transform.position.y;
Instantiate(guyGameObject, new Vector3(instX, instY, 0), Quaternion.identity);

This code grabs the x and y coordinates of the new GameObject, plugs them into the Instantiation code, and creates a clone at those same coordinates. This form of Instantiation can be very handy for creating enemy spawn points or weapons that fire projectiles from a single spot.

Combining Instantiate and Destroy

Ready to Destroy your creations? There's one more step before you can do so via script: Add the Instantiated objects to another GameObject variable. In this case we'll use a local variable to do the job:

GameObject objectToDestroy = Instantiate(guyGameObject, new Vector3(instX, instY, 0), Quaternion.identity);
Destroy(objectToDestroy);

Typically you would not create and then immediately Destroy a GameObject, particularly not in the same function, but the point here is clear: Declare the new Instance as objectToDestroy, then Destroy that GameObject. No more Instance, and no error to boot since it is an Instance and not a prefab.

A full example of a script that could create and Destroy Instances might look something like this:

Press G and an Instance of guyGameObject is created at the coordinates of instantiateObjectHere. Press F and that new GameObject, now defined as newInstance, is Destroyed. That about does it!

This is, of course, not the only way you can implement either Instantiate or Destroy in your games. Objects can be created and destroyed when:

  • A GameObject strikes the Collider of another GameObject;
  • A timer reaches a certain count;
  • A boolean is triggered;
  • A GameObject reaches a certain speed; and
  • Plenty others. There are probably hundreds of small, specific scenarios which could trigger the creation or destruction of an Instance.

One Final Note!

It is worth knowing that there's one other way to create an Instance of a GameObject, and that's to drag a prefab into the Game view from your Assets. This is often done to design pre-determined situations into a game: for example, if you knew you wanted an enemy to appear at a specific spot on a map, you would drop it into the game. This would count as an Instance and could be destroyed without an error. This is also how you would create spawn points in the first place, so there is a lot of mixing-and-matching of the two methods of Instantiation that you'll wind up using in just about any Unity game.

Comments

Submit a Comment

No comments yet.

working

This website uses cookies

As a user in the EEA, your approval is needed on a few things. To provide a better website experience, owlcation.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://maven.io/company/pages/privacy

Show Details
Necessary
HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
LoginThis is necessary to sign in to the HubPages Service.
Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
AkismetThis is used to detect comment spam. (Privacy Policy)
HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
Features
Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
MavenThis supports the Maven widget and search functionality. (Privacy Policy)
Marketing
Google AdSenseThis is an ad network. (Privacy Policy)
Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
Index ExchangeThis is an ad network. (Privacy Policy)
SovrnThis is an ad network. (Privacy Policy)
Facebook AdsThis is an ad network. (Privacy Policy)
Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
AppNexusThis is an ad network. (Privacy Policy)
OpenxThis is an ad network. (Privacy Policy)
Rubicon ProjectThis is an ad network. (Privacy Policy)
TripleLiftThis is an ad network. (Privacy Policy)
Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
Statistics
Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)
ClickscoThis is a data management platform studying reader behavior (Privacy Policy)