Search Unity

Code to destroy collected object not working

Discussion in 'Getting Started' started by JackFranklin96, Jan 21, 2015.

  1. JackFranklin96

    JackFranklin96

    Joined:
    Jan 21, 2015
    Posts:
    7
    Hi I've being using the code below to destroy an object when the player character makes contact with the trigger for the object but it hasn't worked and I can't figure out why any advice would be great. Thanks

    Code (csharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class Collisioncod : MonoBehaviour {
    5.  
    6. void OnTriggerEnter2D (Collider2D obj) {
    7. if(obj.gameObject.tag=="MapPiece"){
    8. Destroy (obj.gameObject);
    9. }
    10. }
    11. }
     
    Last edited by a moderator: Jan 22, 2015
  2. KaaPex

    KaaPex

    Joined:
    Jan 17, 2015
    Posts:
    16
    Write some test output into console to check that objects are collide.
    Code (CSharp):
    1.  
    2. void OnTriggerEnter2D (Collider2D obj)
    3. {
    4.       print ("Object with tag collide me:" + obj.gameObject.tag);
    5.       if(obj.gameObject.tag=="MapPiece")
    6.       {
    7.              print ("Yes we are!!!");
    8.              Destroy (obj.gameObject);
    9.        }
    10. }
    11.  
     
  3. JackFranklin96

    JackFranklin96

    Joined:
    Jan 21, 2015
    Posts:
    7
    Hi I'm wondering how to do that cause-I'm kind of a noob
     
  4. KaaPex

    KaaPex

    Joined:
    Jan 17, 2015
    Posts:
    16
  5. DustyMcp

    DustyMcp

    Joined:
    May 23, 2013
    Posts:
    25
    Code (CSharp):
    1. void OnTriggerEnter2D (Collider2D collision)
    2. {
    3. if(collision.gameObject.tag=="player")
    4. {
    5. Destroy (gameObject,0f);
    6. }
    7. }
    8. }
    Try this.
    Attach this script to the target you need destroyed.

    Pseudo:
    if your collision is with the object with the tag "player" destroy the gameobject the script is attached to.
     
  6. JackFranklin96

    JackFranklin96

    Joined:
    Jan 21, 2015
    Posts:
    7
    Hi

    The script you gave me still didn't work the word player is highlighted in orange if that makes a difference.

    Thanks