- Home /
How to Find Owner of a Trigger?
Hello Everyone,
I am currently trying to adapt my method of allowing the player to initiate dialogue with multiple NPCs.
At the moment I have where the NPC checks if the player has entered it's Trigger:
void OnTriggerEnter (Collider collider){
if (_player == null && collider.CompareTag("Player")){
_player = collider.gameObject;
}
else{
return;
}
_playerComponent = _player.GetComponent<PlayerStateMachine>();
_playerComponent.InDialogueTrigger = true;
}
If the Player enter's the trigger it tells the Player Script that it is in the trigger.
Once the Player knows that it is in the dialogue trigger it starts shooting a raycast to check if the player is facing the NPC or not.:
if(_inDialogueTrigger && !_dialogueIsPlaying){
if(Physics.Raycast(_raycastOrigin.position, _raycastOrigin.forward, out RaycastHit hit, 2f) && hit.transform.tag == "NPC"){
_facingNPC = true;
_uiManagerComponent.EnableInteractPrompt();
_npc = hit.transform.gameObject.GetComponent<NPCScript>();
}
else {
_facingNPC = false;
_uiManagerComponent.DisableInteractPrompt();
}
}
else {
_uiManagerComponent.DisableInteractPrompt();
}
However, if there is another NPC near enough since it is just checking for the NPC tag it will still enable the interact prompt and attempt to trigger the other NPCs dialogue.
My question is: Is there a way I can have the raycast make sure the hit is the owner of the trigger it is standing in? I could just shorten the distance to be really short and not have NPCs stand next to each other but that feels like a hack rather than just doing it correctly.
Answer by Caeser_21 · Feb 16 at 01:33 PM
First, create an empty GameObject in the "PlayerStateMachine" script (Called "NPCObj").
Then change the 'NPC' script to this :
void OnTriggerEnter (Collider collider){
if (_player == null && collider.CompareTag("Player")){
_player = collider.gameObject;
}
else{
return;
}
_playerComponent = _player.GetComponent<PlayerStateMachine>();
_playerComponent.InDialogueTrigger = true;
_playerComponent.NPCObj = this.gameObject
}
Then, instead of :
if(Physics.Raycast(_raycastOrigin.position, _raycastOrigin.forward, out RaycastHit hit, 2f) && hit.transform.tag == "NPC")
Type this :
if(Physics.Raycast(_raycastOrigin.position, _raycastOrigin.forward, out RaycastHit hit, 2f) && hit.transform.gameObject == NPCObj)
This should work...
**Thanks to @LinkUpGames for finding an error
Also...if the syntax is a bit hard to understand, I will re-word it
That worked perfectly! Thanks so much. A slight change was needed though as "hit.gameObject" is actually "hit.transform.gameObject." but after that, it works exactly as I'd hoped!