在触发器内按下操作键后,销毁属于预制件的游戏对象

时间:2019-10-05 16:12:28

标签: c# unity3d

所以我要制作2D平台。我的关卡由多个平台组成,这些平台都是预制件的一部分。我要这样做,以便当我的玩家按下collider2d内部的一个键(在这种情况下为“ E”)时,玩家上方的平台被破坏,并且平台上的盒子掉下来了。

当扳机内部按下“ E”键时,我的检测工作正常,但无法弄清楚如何仅破坏预制件中的单个平台。

任何帮助将不胜感激!

public class SwitchController : MonoBehaviour
{
    public Collider2D switchCollider;
    public Rigidbody2D player;

    void Start()
    {
        switchCollider = GetComponent<Collider2D>();
    }

    private void OnTriggerStay2D(Collider2D col)
    {
        // var player = col.GetComponent<PlayerController>();
        var actionBtn = PlayerController.action;
        if (player)
        {
            Debug.Log("Collided");

            if (Input.GetKeyDown(KeyCode.E))
            {
                actionBtn = true;
                Debug.Log("Action Pressed");
            }

        }
    }
}

1 个答案:

答案 0 :(得分:0)

如果可能,最简单的解决方案是通过(预制件的)检查器存储平台。
然后,您将在需要时销毁游戏对象,就像这样:

public class SwitchController : MonoBehaviour {

    // ...

    public GameObject targetPlatform;

    private void OnTriggerStay2D(Collider2D col) {
        // ...
        Destroy(targetPlatform); // Destroy the platform.
    }
}

或者,您可以从播放器向上进行广播

public class SwitchController : MonoBehaviour {
    public Collider2D switchCollider;
    public Rigidbody2D player;

    [SerializeField, Tooltip("The layer mask of the platforms.")]
    public LayerMask platformLayerMask;
    void Start() {
        switchCollider = GetComponent<Collider2D>();
    }

    private void OnTriggerStay2D(Collider2D col) {
        var actionBtn = PlayerController.action;

        if (player) {
            if (Input.GetKeyDown(KeyCode.E)) {
                actionBtn = true;
                // Raycast upwards from the player's location.
                // (Raycast will ignore everything but those with the same layermask as 'platformPlayerMask')
                RaycastHit2D hit = Physics2D.Raycast(player.transform.position, Vector2.up, Mathf.Infinity, platformLayerMask);

                if (hit.collider != null) {
                    // Destroy what it hits.
                    Destroy(hit.transform.gameObject);
                }
            }
        }
    }
}

与第一个解决方案相比,该解决方案更具动态性。
您只需要在检查器中设置平台的Layers