Nitin Rathod
Nitin Rathod

Reputation: 163

Unity2d - Destroying Object using Destroy(gameObject) // it will destroy the object with which the script is attached to

I am Creating Unit2D game & i am new to it , where i have written code for Destroying Player Bullete when it hits to Meteorite(or enemy). I have one Bullete PREFAB. to which Destroybullete script is attached. where i have written normal code under TRIGGER function (C# script).

void OnTriggerEnter2D(Collider2D col)
{
    if(col.gameObject.tag == "meteorite") // have given meteorite tag to meteorite PREFAB
    {
        Destroy(gameObject)
    }
} 

I want to know is it correct way to destroy any object. because it keeps showing me msg that "Avoid destroying object to avoid data loss".

AND THE MAIN THING. This code works well in Unity Editor ( Build Settings set to android). But if i build and create APK of it .......... on my android mobile(redmi 1s) , it is not working.Bullete starts firing automatically ( as required) but as any bullete hits meteorite than game lags for miliseconds and bulletes stops firing....AND THE SAME CODE WORKS FINE UNDER UNITY.

DOES TO MEAN I HAVE KILLED bullete prefab for ever by writing Destroy(gameObject).

Upvotes: 0

Views: 1465

Answers (1)

Neven Ignjic
Neven Ignjic

Reputation: 679

The correct way to destroying objects is not destroying them :).

The msg you are getting in console inside Unity is just a warning to try avoiding destroying objects, main reason is being that Destroy and Instantiate are VERY expensive commands and they are often used a lot (like your example, instantiating every bullet then destroying it).

Reason why it works well on PC is because you have much higher processing power of hardware compared to mobile and the lag you are getting on mobile is the time it takes to finish Destroy command (or Instantiate).

The way you can avoid using Instantiating and Destroying objects is by using object pooling, it is a simple way to reuse small pool of objects.

Here is a simple way how you would implement it: 1. Instantiate let's say 5 bullets at start and hide them inside barrell or something like that. 2. Fire the first bullet from barrel and when it hits something just move it back to barrel at the end of array. 3. Keep reusing the bullets

You have good in-depth explanation about object pooling here : https://unity3d.com/learn/tutorials/modules/beginner/live-training-archive/object-pooling

But you can get away with much less understanding of object pooling, if this is too long try searching online something like "Unity3D object pooling" and find simpler tuorial.

Upvotes: 1

Related Questions