Search Unity

Question Multiples gameObjects with same script command 1 bool in an other script

Discussion in 'Scripting' started by Saw9yer, Jan 17, 2022.

  1. Saw9yer

    Saw9yer

    Joined:
    Sep 19, 2020
    Posts:
    72
    Hello everyone,

    I have 10 interlocutors, i want my interlocutors start a dialogue when they are in contact with the player :

    Code (CSharp):
    1. void OnTriggerStay2D(Collider2D col)
    2.     {
    3.         if (col.gameObject.CompareTag("Player"))
    4.         {
    5.             player.GetComponent<PlayerInteract>().hasAnInterlocutor = true;
    6.         }
    7.     }
    8.  
    9.     void OnTriggerExit2D(Collider2D col)
    10.     {
    11.         if (col.gameObject.CompareTag("Player"))
    12.         {
    13.             player.GetComponent<PlayerInteract>().hasAnInterlocutor = false;
    14.         }
    15.     }
    The code above works well if i only have 1 interlocutor in my scene.
    But if i have more than one, hasAnInterlocutor stay false.
    I understand why but i can't find a way so set hasAnInterlocutor = true if you have 1 interlocutor in contact and false only if i have 0 interlocutor in contact.
     
  2. TheFunnySide

    TheFunnySide

    Joined:
    Nov 17, 2018
    Posts:
    200
    You need to introduce a counter and make hasAnInterlocutor into a Property that checks the counter.

    Code (CSharp):
    1. int   interlocutorCounter=0;
    2.  
    3. bool HasAnInterLocutor{get => interlocutorCounter>0;}
    4.  
    5. [LIST=1]
    6. [*]void OnTriggerStay2D(Collider2D col)
    7. [*]    {
    8. [*]        if (col.gameObject.CompareTag("Player"))
    9. [*]        {
    10. [*]            player.GetComponent<PlayerInteract>().interlocutorCounter++;
    11. [*]        }
    12. [*]    }
    13. [/LIST]
    14.  

    There are still ways this might break though. Hard to predict what happens when you delete Objects and / or teleport stuff arround.
     
  3. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,697
    Amen brother. This sort of "rely on perfect ENTER / EXIT calls" matchup code gives me hives.

    Instead have the NPCs each ask they distance to the player, and when it is within a certain amount consider the player worthy of talking to.

    Elements you need:

    - a way for NPCs to ask if the player is nearby them

    - a UI for the NPC to bring up when player is close ("Talk to me")

    - a way for the NPC to start the conversation when prompted