Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by nethsajo1998 · Dec 08, 2018 at 11:20 AM · characterunity5npc

Press f to interact with NPC or objects

How do I change the method used for initiating the interaction. Instead of clicking object, check if within a certain radius of an object when you hit a key on your keyboard.

If within 1 unit, the player gets a message that they can press f to interact. When f is pressd, get the object they're close to and handle the interaction the same way.

PS. I'm using box collider.

Here are the script that I found. I tried this but once I start the game and press F key, its working. But I want the player to press the F key once the character is inside the collider of an object.

WorldInteraction

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 using UnityEngine.AI;
 
 public class WorldInteraction : MonoBehaviour {
     NavMeshAgent playerAgent;

 void Start() {
     playerAgent = GetComponent<NavMeshAgent>();
 }

 void Update() {
     if (Input.GetMouseButtonDown(0) && !UnityEngine.EventSystems.EventSystem.current.IsPointerOverGameObject()) {
         GetInteraction();
     }
 }

 void GetInteraction() {
     Ray interactionRay = Camera.main.ScreenPointToRay (Input.mousePosition);
     RaycastHit interactionInfo;
     if(Physics.Raycast(interactionRay, out interactionInfo, Mathf.Infinity)) {
         GameObject interactedObject = interactionInfo.collider.gameObject;
         if (interactedObject.tag == "Interactable Object") {
             interactedObject.GetComponent<Interactable>().MoveToInteraction(playerAgent);
         } else {
             playerAgent.destination = interactionInfo.point;
         }
     }
 }

}

Interactable

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 using UnityEngine.AI;
 
 public class Interactable : MonoBehaviour {
     public NavMeshAgent playerAgent;

 public virtual void MoveToInteraction(NavMeshAgent playerAgent) {
     this.playerAgent = playerAgent;
     playerAgent.destination = this.transform.position;

     Interact();
 }

 public virtual void Interact() {
     Debug.Log ("Interacting with base class.");
 }

}

NPC

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 
 public class NPC : Interactable {

 public override void Interact() {
     Debug.Log ("Interacting with NPC.");
 }

}

Comment
Add comment · Show 5
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image nicholasw1816 · Dec 10, 2018 at 12:15 PM 0
Share

Yeah there's a way to do that, use OverlapSphere to find coliders with respect to your specified position, radius, and layer.

 public class YourScript : $$anonymous$$onoBehaviour
 {
     private float myRadius = 20;
     public Layer$$anonymous$$ask myLayers;
 
     private void Update()
     {
         if (Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.F))
         {
             Collider[] objectToDetect = Physics.OverlapSphere(transform.position, myRadius, myLayers);
             if (objectToDetect.Length > 0)
             {
                 if (objectToDetect[0].gameObject.tag == "tagYouLookingFor")
                 {
                     //Do your thing
                 }
             }
         }
     }
 }

avatar image nethsajo1998 nicholasw1816 · Dec 16, 2018 at 03:45 PM 0
Share

Well, I have two object tags to be interact by the player. Portal and NPC (Interactable Object). On Portal tag, the player will press the Enter button to select locations and for the NPC the player needs to press the F key to interact with NPC. I'm just confused. Are these correct? Correct me if I'm wrong.

 private void Update()
      {
          if (Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.F))
          {
              Collider[] objectToDetect = Physics.OverlapSphere(transform.position, myRadius, myLayers);
              if (objectToDetect.Length > 0)
              {
                  if (objectToDetect[0].gameObject.tag == "Portal")
                  {
                      //Do your thing
                  }
              }
          }
          else if (Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.F))
          {
              Collider[] objectToDetect = Physics.OverlapSphere(transform.position, myRadius, myLayers);
              if (objectToDetect.Length > 0)
              {
                  if (objectToDetect[0].gameObject.tag == "Interactable Object")
                  {
                      //Do your thing
                  }
              }
          }
      }
avatar image nethsajo1998 nicholasw1816 · Dec 24, 2018 at 01:21 AM 0
Share

What if I have 2 different tags to be interact like Portal and Interactable Objects? Can you check my code above? @nicholasw1816

avatar image nethsajo1998 nethsajo1998 · Dec 25, 2018 at 06:25 AM 0
Share

What If I have 2 different tags? Lets say I have Portal and Interactable Objects tag. On the Portal tag, the player needs to hit the Enter $$anonymous$$ey to select locations while on the Interactable Objects or anything, the player needs to hit the F key. How would I do that on your code? Thanks.

avatar image nethsajo1998 nicholasw1816 · Dec 25, 2018 at 06:26 AM 0
Share

What If I have 2 different tags? Lets say I have Portal and Interactable Objects tag. On the Portal tag, the player needs to hit the Enter $$anonymous$$ey to select locations while on the Interactable Objects or anything, the player needs to hit the F key. How would I do that on your code? Thanks.

3 Replies

· Add your reply
  • Sort: 
avatar image
1

Answer by dan_wipf · Dec 08, 2018 at 11:31 AM

well instead of this:

 void Update() {
      if (Input.GetKeyDown(KeyCode.F)&& !UnityEngine.EventSystems.EventSystem.current.IsPointerOverGameObject()) {
          GetInteraction();
      }
  }


you could use your box collider as trigger. then check if the plyaer is inside the collider.

 //like this
 
 void OnTriggerStay(Collider other){
     if (other.tag == “Player” && Input.GetKeyDown(KeyCode.F)){
     //your code
 }
Comment
Add comment · Show 18 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image nethsajo1998 · Dec 10, 2018 at 07:36 AM 0
Share

Its not working.

avatar image kaosermail nethsajo1998 · Dec 10, 2018 at 11:20 AM 0
Share

You need to have a rigidbody on one of the objects (you or the npc) and have isTriggered set to true on yourself ;)

avatar image nethsajo1998 kaosermail · Dec 10, 2018 at 12:07 PM 0
Share

$$anonymous$$y character has rigidbody and the isTriggered also checked.

Show more comments
avatar image dan_wipf nethsajo1998 · Dec 10, 2018 at 12:00 PM 0
Share

well i dont know your experience with unity, but what you want is a trigger zone which if you, the player is inside can interract with what ever throught pressing f. this is achieved by a collider set to trigger, and then inside a script look for the player if he is inside and pressed the key. am i right if this is what you want?

avatar image nethsajo1998 dan_wipf · Dec 10, 2018 at 12:12 PM 0
Share

Ins$$anonymous$$d of object.tag == "Player" can I use object.tag == Interactable Object" ?

Show more comments
avatar image
1

Answer by Username801 · Feb 20, 2020 at 02:08 PM

I am a complete noob to unity. However, found a tutorial that seems good: link text.

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
0

Answer by berndunity · Dec 12, 2018 at 06:51 AM

You should set a bool to true when the player collides, as dan_wipf said, and use that bool inside update like.

      public bool open = false;

  if (other.tag == “Player”){
          open = true;
          }
     
 Update(){
  if (Input.GetKeyDown(KeyCode.F)){
 //your code.
 }
 }

I think you get the idea, because OnTriggerStay is called once and update every frame.

Comment
Add comment · Show 10 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image nethsajo1998 · Dec 13, 2018 at 12:53 AM 0
Share

Will I add this script inside the OnTriggerStay?

avatar image berndunity nethsajo1998 · Dec 14, 2018 at 04:08 PM 0
Share

Sorry for my late answer, but I would use OnTriggerEnter(){}

avatar image dan_wipf berndunity · Dec 14, 2018 at 04:59 PM 0
Share

well then you cant call onkeydown, them you have to set a bool to true and inside the update part, call onkeydown

Show more comments
avatar image nethsajo1998 · Dec 14, 2018 at 08:23 AM 0
Share

Its working now, but the problem is when I pressed the f key it doesn't call the GetInteraction method.

avatar image berndunity · Dec 14, 2018 at 04:07 PM 0
Share

Can you send the updated code, because now I can't know how it looks like.

P.S. you haven't put the Update() in OnTriggerEnter()

avatar image nethsajo1998 berndunity · Dec 16, 2018 at 03:30 PM 0
Share

Here's what I did. On the Portal tag there's a little problem. Why I got too much selection buttons of location? I just console the hasInteracted boolean and I got 18 response of "True". See screenshot below.

 //World Interaction
 void OnTriggerStay(Collider interactedObject) {
         if (interactedObject.gameObject.tag == "Interactable Object" && Input.Get$$anonymous$$eyDown ($$anonymous$$eyCode.F)) 
         {
             GetInteraction(interactedObject);
         } 
         else if (interactedObject.gameObject.tag == "Pickupable Object" && Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.LeftControl)) 
         {
             GetInteraction(interactedObject);
         } 
         else if(interactedObject.gameObject.tag == "Portal" && Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.Return)) 
         {
             GetInteraction(interactedObject);
         }
     }
 
     void GetInteraction(Collider interactedObject)
     {
         hasInteracted = true;
         interactedObject.GetComponent<Interactable>().Interact();
         messagePanel.SetActive(false);
     }
 
 //Portal
 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 
 public class Portal : ActionItem {
     public Vector3 TeleportLocation { get; set; }
     [SerializeField]
     private Portal[] linkedPortals;
     private PortalController portalController { get; set; }
 
     void Start () {
         portalController = FindObjectOfType<PortalController>();
         TeleportLocation = new Vector3(transform.position.x + 5f, transform.position.y, transform.position.z);
     }
 
     public override void Interact() {
         portalController.ActivatePortal(linkedPortals);
     }
 }
 
 //PortalController
 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 using UnityEngine.UI;
 
 public class PortalController : $$anonymous$$onoBehaviour {
     [SerializeField]
     private Button button;
     private Portal[] portal;
     private Player player;
     private GameObject panel;
 
     void Start() {
         player = FindObjectOfType<Player> ();
         panel = transform.Find ("PanelPortals").gameObject;
     }
 
     public void ActivatePortal(Portal[] portals) {
         panel.SetActive (true);
         for (int i = 0; i < portals.Length; i++) {
             Button portalButton = Instantiate (button, panel.transform);
             portalButton.GetComponentInChildren<Text> ().text = portals [i].name;
             int x = i;
             portalButton.onClick.AddListener (delegate {
                 OnPortalButtonClick (x, portals [x]);
             });
         }
     }
 
     void OnPortalButtonClick(int portalIndex, Portal portal) {
         player.transform.position = portal.TeleportLocation;
         foreach (Button button in GetComponentsInChildren<Button>()) {
             Destroy (button.gameObject);
         }
         panel.SetActive (false);
     }
 }


alt text

avatar image berndunity nethsajo1998 · Dec 18, 2018 at 09:13 AM 0
Share
 public void ActivatePortal(Portal[] portals) {
      panel.SetActive (true);
      for (int i = 0; i < portals.Length; i++) {
          Button portalButton = Instantiate (button, panel.transform);
          portalButton.GetComponentInChildren<Text> ().text = portals [i].name;
          int x = i;
          for ( int p = 0; p < portals.Lenght; p++){
          if (p.name == i.name ){
 `           Destroy(p.gameObject);
         }
           }
          portalButton.onClick.AddListener (delegate {
              OnPortalButtonClick (x, portals [x]);
          });
      }
  }

$$anonymous$$ake a for loop inside the other for loop to check if there aren't any double buttons, if there are then destroy it.(I can't check if this will work).

Show more comments

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

150 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

How can I make companion npcs follow the player's path, ala Chrono Trigger? 2 Answers

How to handle multiple animation variants 1 Answer

RPG style character with multiple items 1 Answer

how to add a .anim or fbx animation to my NPC/character? 0 Answers

Help Animate my NPC's 0 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges