- Home /
Trigger collider only activate when player is inside it
I have a crate that drops into my world and I want to to stay there until the player comes along and trigger the trigger collider. The problem is my crate reacts to anything it touches instead of only the player.
public class Crate : MonoBehaviour {
// Variables
Player player;
GunController gunController;
void Start() {
player = FindObjectOfType<Player>();
gunController = player.GetComponent<GunController>();
}
void OnTriggerEnter(Collider other) {
if (other.tag == "Player") {
gunController.EquipGun(gunController.allGuns[Random.Range(0, 4)]);
}
Destroy(gameObject);
}
}
I'm curious if changing your tag comparison line to the following changes the way it behaves:
if (other.gameObject.tag == "Player") {
I only ask because the script API says that your other.tag is a component.tag, rather than a GameObject.tag. Not sure if there is a difference, but they made two different script API pages for them for some reason.
Also, something I've done in the past rather than checking for tags is checking for a script on the object, like a script that is only on the player objects. I used that at the time to check if an object was under AI control by checking for an attached AI script, but could work here.
if (other.gameObject.GetComponent<ScriptOnlyOnPlayers>()) {
Answer by TeohRIK · Apr 20, 2017 at 01:15 AM
void OnTriggerEnter(Collider other) {
if (other.gameObject.tag == "Player") {
gunController.EquipGun(gunController.allGuns[Random.Range(0, 4)]);
Destroy(gameObject);
}
}
Put your destroy inside the if function, else anything collide then the destroy function will be called