2
votes

I have the following script that is supposed to detect the collision between two objects (BoxCollider2D is a trigger and CircleCollider2D is a normal collider)

public class ArcadeScore : MonoBehaviour {

    public BoxCollider2D bc;
    public CircleCollider2D cc;

    private int score;

    // Use this for initialization
    void Start () {
        score = 0;
    }

    // Update is called once per frame
    void Update ()
    {
        if (bc.IsTouching(cc))
        {
            Debug.Log("collision detected");
            score++;
        }
    }
}

But the script doesn't print anything in the console, so I was wondering if it was possible to detect a collision between a trigger and a normal collider from an external script?

1
"External Script"..... What does that even mean? - Programmer
@Programmer To add an empty GameObject, attach a script to it and use it to detect collision - John
@Programmer I also tried by using OnTriggerEnter2D() and making a public Collider2D and attaching my trigger there, but still nothing. - John
It's simple called "script". Did you check "is trigger" on the colliders? - Programmer
@Programmer Yes I did - John

1 Answers

0
votes

You have to use OnCollisionEnter2D not IsTouching. IsTouching is used to detect when they are touching over frames and this may not be true. The script with OnCollisionEnter2D function must be attached to the GameObject with the collider not to an empty GameObject.

the problem is that I constantly destroy that object and all the values revert back to 0

You have to separate your game logic, score system code with the objects that destroys during run-time. Basically, your game logic, score system code should not be attached to the object that destroys itself. They should be attached to an empty GameObject.

The trick is to find the score system Object, get its script then update the score before destroying the object that collided.

The ScoreSystem script(Attach to an empty GameObject):

public class ArcadeScore : MonoBehaviour 
{
    public int score;

    // Use this for initialization
    void Start () {
        score = 0;
    }
}

The Collsion script(Attach to the GameObject with the Collider):

public class CollsionScript: MonoBehaviour 
{
    ArcadeScore scoreSys;

    void Start()
    {
        //Find the ScoreSystem GameObject
        GameObject obj = GameObject.Find("ScoreSystem");
        //Get the ArcadeScore script
        scoreSys = obj.GetComponent<ArcadeScore >();
    }

    void OnCollisionEnter2D(Collision2D coll) 
    {
        if (coll.gameObject.tag == "YourOtherObject")
        {
            scoreSys.score++;
            //You can now destroy object
            Destroy(gameObject);
        }
    }
}