DiogoSaraiva
DiogoSaraiva

Reputation: 1665

Collider2D trigger on a different gameObject C# Unity3D not working

In Unity, how can my code detect when a trigger occurs with a specific distinct object?

I already tried several things, such as:

using UnityEngine;
using System.Collections;

public class PlayerController : MonoBehaviour {

    public GameObject DualCannon_PU;

    void OnTriggerEnter2D (Collider2D coll) {
        if (coll.name == "DualCannon_PU") {
            Debug.Log ("DualCannon PowerUp");
        }
    }
}

But it doesn't work: it doesn't trigger anything and "DualCannon PowerUp" does not appear in console.

In player gameObject "is trigger" is checked and my powerUp (DualCannon_PU) "is trigger" is not checked.

I noticed that I had 2 "Player Controller (Scripts)", I deleted the first one but the problem still persists...


an example of what I want:

I have 4 gameObjects and both have 2D Colliders

Condition I want:

  1. A is triggered by B, C, and D
  2. When B triggers with A in A script (Player.cs) executes: health -= laser.GetDamage();
  3. When C triggers with A in A script (Player.cs) executes: health = health + 10;
  4. When D triggers with A in A script (Player.cs) executes isDualCannon = true

Upvotes: 2

Views: 1322

Answers (1)

Chanisco Tromp
Chanisco Tromp

Reputation: 38

first you need to:

Put the "Is trigger" On

Make sure you're colliders are in the border of the gameObject(edit Colliders and drag until the green lines are in the corners)

If the error still consist comment on the answer and I will see what I can do

It works fine with mine:

The Block that hits

enter image description here

This guy will hit this guy using this code:

void OnTriggerEnter2D(Collider2D col){
        Debug.Log ("notset = " + col.name);
    }

Upvotes: 1

Related Questions