Boolean problem (231097)

I want to let when my plane touches the powerbox, the powerbox disappears, and the ammo will shoot according to the motion of the plane. However, if I type destroy(gameObject), the function will only destroy the gameobject and the ammo will not shoot. When I delete destroy(gameObject), the powerbox will not be destroyed. But the ammo will only shoot on one side and will not shoot according to the motion of the plane. I have tried so long.

void Update()
    {

 gameObject.transform.position += new Vector3(0, -0.02f, 0);
        ammo2time += Time.deltaTime;
        if (hitpowerbox == true)
        {
            if (ammo2time > 0.30f) 
            {

                Vector3 ammo2_pos = Ship.transform.position + new Vector3(2, 0.1f, 0);

                Instantiate(ammo2, ammo2_pos, Ship.transform.rotation);

                ammo2time = 0;
                
            }
            else
            { }

        }

    }

    void OnTriggerEnter2D(Collider2D col) 
    {
        if (col.tag == "plane")
        {

            hitpowerbox = true;


        }
        Destroy(gameObject);
    }

It seems, as has been mentioned in a [previous answer to your question][1], you're (for starters) destroying the object before it gets a chance to do anything in the next Update. [1]: https://answers.unity.com/questions/1696831/why-the-value-of-caseswitch-cant-change.html

put the hitpowerbox field on another script on the plane with the update logic instead of the bullet then in ur on trigger enter u can get the plane script using GetComponent and then set hitpowerbox = true on that script.

And delay the destriy function? public static void Destroy(Object obj, float t = 0.0F); So Destroy (Object, 3); to delay it 3 seconds

1 Answer

1

As others have said, you’re destroying the object as soon as it’s hit, and before it has a chance to spawn the bullet.

So you want to move the Destroy call to after the ammo is spawned. I would do this in a coroutine, that makes it much easier to implement your delay, and keeps your Update function cleaner (ie it only contains things that happen on every frame).

I’m not 100% sure this gives you what you want as it’s not clear what object your script is on or what “Ship” is, but it’d look something like this…

Coroutine hitCoroutine;

void IEnumerator HandleHit()
{
    yield return WaitForSeconds(0.3f);
    Vector3 ammo2_pos = Ship.transform.position + new Vector3(2, 0.1f, 0); 
    Instantiate(ammo2, ammo2_pos, Ship.transform.rotation);
    Destroy(gameObject);
}

void OnTriggerEnter2D(Collider2D col) 
{
    if (col.tag == "plane")
    {
        if (hitCoroutine == null) // this is to ensure that it only happens once
        {
            hitCoroutine = StartCoroutine(HandleHit());
        }
    }
}

void Update()
{ 
   gameObject.transform.position += new Vector3(0, -0.02f, 0);
}