'How do I trigger an event with a specific game object in Unity?
I have a problem with a trigger. Basicaly I want the the trigger to work only when the player pass on it. But if an enemy collide with it or a bullet collide with it, it gets activated. I tried to put a tag on the player but it doesn't seems to work because the trigger doesn't recognize the player or the bullet shooted from his gun. Here is the script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class StartTrigger : MonoBehaviour
{
public GameObject Player;
public GameObject Spawns;
public GameObject Trigger;
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.CompareTag("Player"))
{
Spawns.SetActive(true);
}
}
void OnTriggerExit2D(Collider2D other)
{
Trigger.SetActive(false);
}
Solution 1:[1]
void OnTriggerEnter2D(Collider2D other)
{
print("Something entered the trigger");
if (other.CompareTag("Player"))
{
print("Player entered the trigger");
Spawns.SetActive(true);
}
}
void OnTriggerExit2D(Collider2D other)
{
print("Something has exit the trigger");
if (other.CompareTag("Player"))
{
print("Player has exit the trigger");
Trigger.SetActive(false);
}
}
If my code not working:
- Make sure that you have tag on the player
- Check tag spelling in code
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | R1nge |
