Search Unity

Unity Interaction System

Discussion in 'Scripting' started by generaltofu203, Feb 4, 2019.

  1. generaltofu203

    generaltofu203

    Joined:
    May 9, 2018
    Posts:
    40
    Hello everyone,
    I need help with implementing an interaction system for a first person game. It's basically like any other major survival game where there is a small dot/cross hair and then if you hover over something you interact with it. ie pick it up, use it, etc. I can't really find any tutorials so is anybody willing to help me? All I know is that it should use raycasts right?

    Thanks guys
     
  2. beanie4now

    beanie4now

    Joined:
    Apr 22, 2018
    Posts:
    311
    Place this guy on your character. It will return you the gameobject you hit with the raycast every time you call it. It also has a debug ray so you can make sure everything is in the correct direction for testing.

    Code (CSharp):
    1. private GameObject DetectInteractable()
    2.     {
    3.         Debug.DrawLine(_Cam.transform.position, _Cam.transform.position +_Cam.transform.forward *2, Color.red);
    4.         RaycastHit Hit;
    5.         if(Physics.Raycast(_Cam.transform.position, _Cam.transform.forward,out Hit, 4,layerMask))
    6.         {
    7.             savedHitPoint = Hit.point;
    8.             return Hit.transform.gameObject;
    9.         }
    10.         else
    11.         {
    12.             savedHitPoint = Vector3.zero;
    13.             return gameObject;
    14.         }
    15.     }
    also dont forget to make a savedHitPoint variable to store that hit location
     
  3. generaltofu203

    generaltofu203

    Joined:
    May 9, 2018
    Posts:
    40
    Thank you for replying but I'm wondering why the hit location needs to be stored? Isn't what the raycast hit enough?
     
  4. generaltofu203

    generaltofu203

    Joined:
    May 9, 2018
    Posts:
    40
    Oh also, is this supposed to be on the camera or the player? because I have them as 2 seperate game objects, is there anything else I should add because it doesn't know what _cam is or saveHitPoint variable
     
  5. beanie4now

    beanie4now

    Joined:
    Apr 22, 2018
    Posts:
    311
    you can define _cam using _cam = camera.main
    savehitpoint is defined with Vector3 saveHitPoint;
    Also, you don't HAVE to save the position, its will just come in useful later.


    You really need to watch some tutorials this is more intermediate level, seems you need to learn the basics.
     
  6. generaltofu203

    generaltofu203

    Joined:
    May 9, 2018
    Posts:
    40
    ok thanks