Micha De Haan
Micha De Haan

Reputation: 65

Unity/C# Trigger Making something else dissapear

Im trying to make it so that when i trigger a trigger in Unity, it doesnt remove the trigger, but it does remove what the trigger is attached to. but i cant seem to figure out how to do it.

void OnTriggerEnter(Collider other)
{
    if (other.gameObject.CompareTag("pickup"))
    {
        audio.Play(); //Play it

        other.gameObject.SetActive(false);
        count = count + 1;
        SetCountText();
    }
}

This is an example of what im trying to do, but imagine it trying to set something else to inactive.

Upvotes: 1

Views: 199

Answers (2)

Bizhan
Bizhan

Reputation: 17145

When you deactivate the game object, the attached collider will be deactivated too. If you want to deactivate a game object and let the collider exist you need to distinct between those two, i.e. have two game objects: one just for the collider and one for the actual object. now you can remove the actual object while the collider can continue to function.

The implementation depends on how you are handling the trigger.

case 1:

OnTriggerEnter is written in a script attached to the game object which static collider (ground) is attached to.

static collider is a collider without a rigidbody.

  1. add a child to this game object and put the visuals in it (i.e. renderer or audio source).

  2. add public GameObject Child; to the script.

  3. set the reference of the child via unity inspector window.

  4. deactivate the child instead of collider's gameobject in OnTriggerEnter method: Child.SetActive(false);

case 2:

OnTriggerEnter is written in a script attached to another game object which also has a dynamic collider (ball) and a rigidbody.

dynamic collider is a collider with a rigidbody.

  1. add a child to the game object which the static collider is attached to

  2. add a script to the game object (MyScript)

  3. add public GameObject Child; to the script.

  4. set the reference of the child via unity inspector window.

  5. deactivate the child instead of collider's gameobject in OnTriggerEnter method: (other as MyScript).Child.SetActive(false);

Upvotes: 2

Ludovic Feltz
Ludovic Feltz

Reputation: 11916

When you deactivate an object with gameObject.SetActive(false); you automatically deactivate every component on you object (Renderer, Triggers, Scripts, ...)

There is two options to achieve what you want to do:

  • Use another object as a trigger (a Plane or a Cube and deactivate your object from this new object)

  • Or as suggested by @madjlzz you can deactivate your Renderer and RigidBody

Upvotes: 1

Related Questions