c# - Collider2D 在不同的游戏对象上触发 C# Unity3D 不工作

标签 c# unity3d

在 Unity 中,我的代码如何检测特定不同对象何时发生触发?

我已经尝试了几种方法,例如:

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

但它不起作用:它不会触发任何东西,并且“DualCannon PowerUp”不会出现在控制台中。

在玩家 gameObject 中“is trigger”被选中,而我的 powerUp (DualCannon_PU)“is trigger”没有被选中。

我注意到我有 2 个“播放器 Controller (脚本)”,我删除了第一个但问题仍然存在......


我想要的例子:

我有 4 个游戏对象并且都有 2D 碰撞体

  • A. 玩家飞船(“is trigger”开启)
  • B. 敌人的射弹
  • C. Health PowerUp
  • D. 双炮加电

我要的条件:

  1. A 由 B、C 和 D 触发
  2. 当 B 在 A 脚本 (Player.cs) 中使用 A 触发时执行:health -= laser.GetDamage();
  3. 当 C 在 A 脚本 (Player.cs) 中使用 A 触发时执行:health = health + 10;
  4. 当 D 在 A 脚本 (Player.cs) 中用 A 触发时执行 isDualCannon = true

最佳答案

首先你需要:

打开“是触发器”

确保碰撞器位于游戏对象的边界(编辑碰撞器并拖动直到绿线位于角落)

如果错误仍然包含对答案的评论,我会看看我能做些什么

它在我的身上工作得很好:

The Block that hits

enter image description here

这家伙会打 这家伙 使用此代码:

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

关于c# - Collider2D 在不同的游戏对象上触发 C# Unity3D 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30213395/

相关文章:

unity3d - 如何运行本地 Unity WebGL(文件 ://url) build?

C# "must declare a body because it is not marked abstract, extern, or partial"

c# - 锁定静态字段

c# - 使用vtk调整dicom文件中的窗口级别

c# - 使用鼠标和触摸旋转我的对象(Unity,C#)

unity3d - 在 Unity 3D 中移动游戏对象的最佳方式

mysql - 如何处理从游戏中不断更新的数据库

c# - 场景背景-启动wcf服务

接口(interface)中的C#静态函数

c# - Unity 2018.1.3f1 UI 闪烁问题