0
\$\begingroup\$

I'm trying to modify brackeys dialogue system using raycast in an interactableOjects Script so that I can talk with multiple characters, however, when I talk to Character A it appears Characters B text and if I go to Character B the same text shows up (which in character B's Case wouldn't be a problem haha). is there a way that I can tell my script to identify both different objects and play different script (I mean without having to create different layers or tags)

InteractableObjects Script:

public void PersonInteract()
{
    int layer_mask = LayerMask.GetMask("Person");

    RaycastHit hit;
    if (Physics.Raycast(fpsCam.transform.position, fpsCam.transform.forward, out hit, range, layer_mask))
    {
        Debug.Log("Speak");

        FindObjectOfType<DialogueTrigger>().TriggerDialogue();

    }   
}

DialogueTrigger Script(the one that is attached to the NPC's):

    using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class DialogueTrigger : MonoBehaviour
{
    public Dialogue dialogue;
 
    public void TriggerDialogue()
    {
        Debug.Log("Talk");
        FindObjectOfType<DialogueManager>().StartDialogue(dialogue);
       
    }
 
}
\$\endgroup\$
1
\$\begingroup\$

FindObjectOfType searches your entire scene for the first GameObject with a component matching the type you asked for, even if that object has nothing whatsoever to do with the object you hit with the raycast.

If you want a DialogueTrigger on the object your raycast hit, then you should ask that object for its DialogueTrigger component:

public void PersonInteract()
{
    int layer_mask = LayerMask.GetMask("Person");

    RaycastHit hit;
    if (Physics.Raycast(fpsCam.transform.position, fpsCam.transform.forward, out hit, range, layer_mask))
    {
        if (hit.transform.TryGetComponent(out DialogueTrigger trigger)) {
            trigger.TriggerDialogue();
        }
    }   
}

If your DialogueTrigger component sits at a different level of the hierarchy from the object that has the collider your raycast hits (ie. a child or parent object), then you might want GetComponentInChildren or GetComponentInParent instead.

\$\endgroup\$
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.