Search Unity

Having an issue making two characters interact

Discussion in '2D' started by chazza1991, Feb 20, 2017.

  1. chazza1991

    chazza1991

    Joined:
    Jul 2, 2016
    Posts:
    1
    Hey everyone,

    this is my first attempt at coding my own game and i am a serious beginner!

    anyway i have set up a player and an npc character within my world and i am trying to make them interact with each other. ive set up a box collider with a trigger for my npc character and this is the code i am attempting to use for it:

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;

    public class NPCScript : MonoBehaviour {

    void OnTriggerEnter2D(Collider2D col )
    {
    if (col.CompareTag("Player"))
    {
    Debug.Log("Player Entered Interaction Zone");
    }
    }

    void OnTriggerStay2D(Collider2D col)
    {
    if (col.CompareTag("Player"))
    {
    if (Input.GetKeyDown("e"))
    {
    Debug.Log("Player Interacted With NPC");
    }
    }
    }
    }

    however it only debugs the message to the console when i have the player physically moving inside of the collider and also it is logging the "Player Interacted With NPC" message twice.

    is there something i am doing wrong?

    thanks,
    Charlie.
     
  2. JoeStrout

    JoeStrout

    Joined:
    Jan 14, 2011
    Posts:
    9,859
    Hey Charlie, welcome to the forums!

    Please use code tags when posting code; it makes it so much more readable.

    Here's a tip on Debug.Log: you can specify a GameObject as a second parameter, and then when you click the message in the Console, it will highlight that object in the hierarchy. This is helpful in situations like yours, where you're getting two logs but think there should be only one — maybe your script is on some other object you're not thinking of. Just make it look like this:

    Code (csharp):
    1.    Debug.Log("Player Interacted With NPC", gameObject);
    Otherwise, I don't see any major problems with your code. What do you mean, "it only debugs the message to the console when i have the player physically moving inside of the collider"? Isn't that what you would expect?