Log in or register to post comments

Destroying enemy on touch

November 7, 2011 - 5:47am #1

Hi,

I'm trying to destroy an enemy object as it is touched.

I've attached a virtual button to the enemy and am using the following script (which is attached to the imagetarget rather than the virtual button as in the Soccerball example.)

This is my code:

   // Called when the virtual button has just been pressed:
    public void OnButtonPressed(VirtualButtonBehaviour vb)
    {
        Debug.Log("OnButtonPressed");
		Destroy(this.transform.parent.gameObject);
     

    }

My intention is to destroy the parent of the virtual button that has just been pressed.

Any ideas?

Re: Destroying enemy on touch

November 8, 2011 - 7:05pm #4

Hmm, sorry, virtual buttons need unique names. You should be able to reuse a name after destroying a virtual button that previously had that name, however.

You could always append a counter to the name?

- Kim

Re: Destroying enemy on touch

November 8, 2011 - 3:21pm #3

Works a treat! Thanks Kim.

My issue now comes with multiple enemies. If more than one enemy has the same name on the virtual button, only one of them can be destroyed and the others remain.

Is there a way around this need for unique VB names? Ideally I'd like to instantiate the same enemy multiple times.

Re: Destroying enemy on touch

November 7, 2011 - 8:37pm #2

In that sample the virtual button event handlers are attached to the image targets, so asking for the parent won't get you the soccer ball object. You can write a handler that is meant to be attached to the button object instead. Something like this:

using UnityEngine;
using System.Collections;

public class VBDestroy : MonoBehaviour, IVirtualButtonEventHandler
{
    void Start ()
    {
        VirtualButtonBehaviour vb = GetComponent<VirtualButtonBehaviour>();
        if (vb)
        {
            vb.RegisterEventHandler(this);
        }
    }

    public void OnButtonPressed(VirtualButtonBehaviour vb)
    {
        Debug.Log("OnButtonPressed");
        vb.GetImageTarget().DestroyVirtualButton(vb.VirtualButtonName);
        Destroy(this.transform.parent.gameObject);
    }

    public void OnButtonReleased(VirtualButtonBehaviour vb)
    {
        Debug.Log("OnButtonReleased");
    }
}

Note this destroys the virtual button as well, which might be a good idea if you don't intend to reuse it.

- Kim

Log in or register to post comments