Prevent a Trigger From another trigger unity

时间:2018-07-25 05:28:53

标签: c# unity3d triggers collision-detection

How do i prevent a trigger from triggering when another trigger is activated. When a touch trigger is activated another triggered is activated without (anything noticeable in the code ) forcing that.

[Trigger 1 (The first one to be activated)]

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Trigger1 : MonoBehaviour {

    private void OnTriggerEnter(Collider other)
    {
        Destroy(GameObject.Find("Block2"));
    }
}

[Trigger 2 (the one to be activated after trigger one for no reason)]

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class Level2Win : MonoBehaviour
{
    private void OnTriggerEnter(Collider other)
    {
        SceneManager.LoadScene("level3");
    }
}

Green Block = first trigger Red Block = second trigger

What the level looks like

2 个答案:

答案 0 :(得分:0)

概念是在触发器主体中使用附加的bool变量和if语句。您甚至可以使用内置的“ enabled”属性,记住无论如何都会触发触发器。

public class Trigger1 : MonoBehaviour {
 public Trigger2 trigger2;
 void Start()
  {
    trigger2.enabled=false;
  }
  private void OnTriggerEnter(Collider other)
  {
     trigger2.enabled=true;
  }

}

public class Trigger2 : MonoBehaviour {
private void OnTriggerEnter(Collider other)
{
 if (enabled)
    {do something else}
}

}

答案 1 :(得分:0)

在明确说明您要在触发第一个触发器之后尝试启用第二个触发器之后,以下是添加功能(以您提供的代码为基础)的最少介入方式:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Trigger1 : MonoBehaviour
{

    // Drag your Leve2Win trigger into the following Inspector object slot.
    public Level2Win Trigger2;

    private void Awake()
    {
        Trigger2.enabled = false;
    }

    private void OnTriggerEnter(Collider other)
    {
        Destroy(GameObject.Find("Block2"));
        Trigger2.enabled = true;
    }
}