2
votes

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

  • A. Player ship ("is trigger" is on)
  • B. Enemy projectiles
  • C. Health PowerUp
  • D. Dual Cannon PowerUp

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
1
What do you mean by don't work? Be more specific about your problem.Soner Gönül
@SonerGönül Updated my question... ThanksDiogoSaraiva
What do you mean by "is trigger" and "is the collider"? What exact game objects do you have, what components do they have (rigidbodies and colliders, your scripts) and what are their settings? (Are rigidbodies kinetic? Are colliders set up as triggers?)Max Yankov
@MaxYankov Updated my question again. Thanks for the patienceDiogoSaraiva
Strange, it looks correct. Have you checked which layers collide with which in the physic settings?Max Yankov

1 Answers

1
votes

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);
    }