How to Make a Flexible Interaction System in 2 Minutes [C#] [Unity3D]

Поділитися
Вставка
  • Опубліковано 30 вер 2024
  • In this video I go over the creation of a flexible interaction system in Unity3D.
    Join my Discord! ► / discord
    How to Make Player Movement ► • SMOOTH FIRST PERSON MO...
    Extra Resources ►
    docs.unity3d.c...
    learn.microsof...
    #unity3d #unitytutorials

КОМЕНТАРІ • 118

  • @Rytech_Dev
    @Rytech_Dev  9 місяців тому +8

    For those who want the code itself without the explaining, I have an archive that is in the works in my discord (link in description)

    • @Twisted444
      @Twisted444 7 місяців тому +5

      can you just paste the code as a comment?

    • @novagardenstudios
      @novagardenstudios 7 місяців тому +4

      Why wouldn't you just use pastebin instead of a discord link with a chat that say No Access??

    • @DoompyGames
      @DoompyGames 5 місяців тому

      I want to attach a „grabbed“ object the the interactor. How would you pass the interactor to the interactable, so it can attach itself to the hierarchy of the interactor?

    • @Dootium
      @Dootium 5 місяців тому

      @@novagardenstudios Cuz he's greedy

    • @SageSLAMS
      @SageSLAMS 3 місяці тому

      @@Twisted444 interface IInteractable {
      Public void Interact();
      }
      public class Interactor : MonoBehaviour
      {
      public Transform InteractorSource;
      public float InteractRange;

      void Update() {
      if(Input.GetKeyDown(KeyCode.E)) {
      Ray r = new Ray(InteractorSource.position, InteractorSource.forward);
      if(Physics.Raycast(r, out RaycastHit hitInfo, InteractRange)) {
      if(hitInfo.collider.gameObject.TryGetComponent(out IInteractable interactObj)) {
      interactObj.Interact();
      }
      }
      }
      }
      }

  • @sxsignal
    @sxsignal Рік тому +47

    Great job. One key difference between your videos and many others (not all but most): You explain how things are being used and why. This is great for knuckle draggers like myself

    • @FauxFemale
      @FauxFemale Рік тому +5

      I agree, a lot of videos don't explain the code. When in this video they faded in a bunch of the code on screen at once I was worried they were gonna go "okay just write this don't worry about it" but they really explain how it works here and I'm thankful

  • @kamcio8586
    @kamcio8586 10 місяців тому +15

    incredible tutorial. Very concise, no waffling, explained everything i wanted to know. 5 star review, will come again

  • @Revlos
    @Revlos 10 днів тому +1

    My second if statement doesn't seem to be triggering:
    void Update() {
    if (Input.GetKeyDown(KeyCode.E)) {
    Ray r = new Ray(InteractorSource.position, InteractorSource.forward);
    if (Physics.Raycast(r, out RaycastHit hitInfo, InteractRange)) {
    Debug.Log("Interactor p1");
    if (hitInfo.collider.gameObject.TryGetComponent(out IInteractable interactObj)) {
    interactObj.Interact();
    Debug.Log("Interactor p2");
    }
    }

    }
    }
    I've attached the interactor to the main camera, set the interactor source to be the main camera and set the range to 100 (just to be sure) And then I've attached the example script to a default cube. When testing, the Interactor p1 message gets pushed to the console, but not the Interactor p2 message, and I don't understand why. Any help would be great!

  • @kalpolproductions8558
    @kalpolproductions8558 Рік тому +12

    Dayumm, lmfao this was way better than creating an if statement for each object

  • @emeraldskits4026
    @emeraldskits4026 Рік тому +27

    For anyone wondering, here's the code:
    interface Interactable
    {
    public void Interact();
    }
    public class IntertheAct : MonoBehaviour
    {
    public Transform InteracterSource;
    public float InteractRange;
    void Update()
    {
    if (Input.GetKeyDown(KeyCode.E))
    {
    Ray r = new Ray(InteracterSource.position, InteracterSource.forward);
    if (Physics.Raycast(r, out RaycastHit hitInfo, InteractRange)) {
    if (hitInfo.collider.gameObject.TryGetComponent(out Interactable interactObj))
    {
    interactObj.Interact();
    }
    }
    }
    }
    }

    • @ZaltInVR
      @ZaltInVR Рік тому

      TY SO MUCHHHH

    • @Monkefinn2
      @Monkefinn2 11 місяців тому

      JUST YOINK Thank you!!!@

  • @fieryninja2374
    @fieryninja2374 Рік тому +9

    Great video, but how would I implement hover? Like it would say click e to interact if I am hovering over the object. Also how do I set up the InteractSource? Do I use the transform of the Camera? Finally what is a good number for the interactRange? Any answers will be greatly appreciated!

    • @tornadre
      @tornadre Рік тому +5

      You would just need to have the raycast every frame in the Update method and have that sign pop up whenever it hits an interactable object
      Put all those objects in their own layer and use a layer mask so the ray can only hit objects on that layer

    • @nahuelhemsi
      @nahuelhemsi 7 місяців тому +2

      @@tornadre FixedUpdate

  • @canadianreviewer4649
    @canadianreviewer4649 Рік тому +5

    When I try to interact in game it’s not doing anything and I believe it has something to do the raycast as interact with the camera does not show the raycast

    • @thedude6389
      @thedude6389 Рік тому +6

      I think I had the same issue and figured it out, not sure if you have either. When you've applied the interactor script to your main camera and also set the "interactor source" as your camera too make sure the interact range isn't 0.

    • @toiletmangaminghd5714
      @toiletmangaminghd5714 Рік тому

      @@thedude6389 Already checked all of that, still not working :/

    • @toiletmangaminghd5714
      @toiletmangaminghd5714 Рік тому +1

      Nevermind, had to make my range higher. Works perfectly now

    • @Lambo_swiper5
      @Lambo_swiper5 Рік тому

      @@toiletmangaminghd5714 I have the same problem what did you set your range to?

    • @necmi_sonmez
      @necmi_sonmez Рік тому

      @@Lambo_swiper5 It will be enough to give 2

  • @cubingfun_
    @cubingfun_ 7 місяців тому +1

    SIMPLE ERROR FIX: people that have abstract script error can make a new script of IInteractable and interface to public interface if you have any no use error then check for capital letters

  • @xkalibvr2876
    @xkalibvr2876 3 місяці тому +3

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    interface IInteractable {
    public void Interact();
    }
    public class Interactor : MonoBehaviour
    {
    public Transform InteractorSource;
    public float InteractRange;
    void Update()
    {
    if (Input.GetKeyDown(KeyCode.E)) {
    Ray r = new Ray(InteractorSource.position, InteractorSource.forward);
    if (Physics.Raycast(r, out RaycastHit hitInfo, InteractRange)) {
    if (hitInfo.collider.gameObject.TryGetComponent(out IInteractable interactObj)) {
    interactObj.Interact();
    }
    }
    }
    }
    }

    • @alexkarivelil6350
      @alexkarivelil6350 2 місяці тому

      Put this on camera ?

    • @RISHABHKUMAR-zk1fu
      @RISHABHKUMAR-zk1fu 33 хвилини тому

      @@alexkarivelil6350 put it on anything but remember to drag and drop camera into InteractSource

  • @huseyinyeldan7998
    @huseyinyeldan7998 Рік тому +30

    your tutorials never work for me for some reason

    • @der-Dritte
      @der-Dritte 5 місяців тому +4

      Did you do it properly?

    • @Legionope
      @Legionope 4 місяці тому +3

      25 upvotes from Unity noobies.

    • @der-Dritte
      @der-Dritte 4 місяці тому +3

      @@Legionope be nice

    • @anabolix_
      @anabolix_ 2 місяці тому

      @@LegionopeLegit you are also noob, so wtf, or why do you have to watch unity tutorial?🤔

    • @Legionope
      @Legionope 2 місяці тому

      @@anabolix_ How exactly does looking around on tutorials, essentially looking at various/multiple ways to get a system done make someone a noob? Especially when you have said system already implemented into your own project and just look at these to see if you can expand on it.

  • @OpxGames
    @OpxGames 5 днів тому

    cant make that work :( error error m8 i copy and pasted, how do i have error

  • @Ejim130
    @Ejim130 2 місяці тому +1

    If your script says public is not a valid term
    Just remove it and it'll still work

  • @novagardenstudios
    @novagardenstudios 7 місяців тому +2

    SO, I've done everything here. Dragged script to camera, made a cube, dragged randgenerator script to it. Set the InteractorSource as Main Camera, set the range to 5. Script's are word for word, character for character. No dice, no output. Nothing happens.

    • @paininkabir4760
      @paininkabir4760 5 місяців тому

      same here. did you solve that?

    • @ransomha
      @ransomha 5 місяців тому

      Did you remember the add the interface to the top of the script? (My bad if that isn't what it's called, i started unity less than a week ago.)
      like this:
      public class KeyGiverScript : MonoBehaviour, IInteractable //THIS
      {
      public void Interact()
      {
      }
      }

    • @mrwaffl333
      @mrwaffl333 3 місяці тому

      nvm

  • @bigglasses2625
    @bigglasses2625 3 місяці тому +1

    It says the name space IInteractable could not be found, there are no errors in studio code, only in the unity engine.

  • @samyplayz261
    @samyplayz261 Рік тому +7

    For those of You, If this didn`t Work, Try Like After writing full interaction code, then put the code in Main Camera and then, Reference Main Camera, Like By Dragging it in Hierachy, and after that, the function is all good to run,
    Sometimes, There should be function which would need you to enable text like You can interact or Pickup or something,
    For that case this is code, Directly in update, and then follow the same steps like creating interface and then reference it to the object script you want and that`s it
    Ray rayEverytime = new Ray(interactionSource.position, interactionSource.forward);
    if(Physics.Raycast(rayEverytime,out RaycastHit hitInfoEverytime, interactionRange))
    {
    if (hitInfoEverytime.collider.gameObject.TryGetComponent(out IInteractableEverytime internObj))
    {
    internObj.InteractEverytime();
    }
    }
    Thank you for the awesome Tutorial

    • @kackebaumzwo
      @kackebaumzwo 6 місяців тому

      ty worked

    • @violetdreamweaver
      @violetdreamweaver 4 місяці тому

      I know this comment is like 8 months old but thank you man

    • @samyplayz261
      @samyplayz261 4 місяці тому

      @@violetdreamweaver Welcome bro

  • @tidectrl
    @tidectrl Рік тому +5

    what do you put for the Interactor Source

    • @bluejay7071
      @bluejay7071 9 місяців тому +1

      The camera

    • @tidectrl
      @tidectrl 9 місяців тому

      @@bluejay7071 thanks pal

    • @ukaszgrabski2811
      @ukaszgrabski2811 7 місяців тому

      @@bluejay7071 if you put the script into the camera then you can refer to this.transform instead.

    • @viniciuspires2629
      @viniciuspires2629 Місяць тому

      @@bluejay7071 oh, thanks man, I was going to create a new game object hahaha

  • @luckybeeyt
    @luckybeeyt Рік тому +3

    what to put in interactorSource?

  • @trispycee
    @trispycee 3 місяці тому +1

    This is awesome. I had some kind of Interacting sphere being generated to try to collide with objects, and it was not working consistently. I have a feeling this will work much better

  • @ga7axy
    @ga7axy Рік тому +1

    I was trying to interact with a door but nothing was happening, then I realized the door didn't have a collider... 😳 (shared this incase any beginner struggled like me 😅)

  • @Astro-Drifter
    @Astro-Drifter 6 місяців тому +1

    Your vid just solved a problem I've been trying to solve for a week. .....You're getting a shout-out in my next dev log

  • @Milzy_TBC
    @Milzy_TBC Рік тому +3

    How do I make it show text when I am in range?

    • @brage2
      @brage2 Рік тому +1

      use the same way you check for interactable objects with a ray, with a second ray that is always casting, to see if you still look at the interactable object and as soon as you don´t disable or empty you text.
      Probably not the best way but works for my use-case.

    • @alexkarivelil6350
      @alexkarivelil6350 2 місяці тому

      @@brage2can you please send me the code

  • @shwoomgloom6763
    @shwoomgloom6763 9 місяців тому +1

    The only issue I have with this tutorial is an Unassigned Reference Exception for the InteracterSource. Is there a way to fix this?

    • @delenter3296
      @delenter3296 8 місяців тому

      @Wesley3268he didn’t show as he assigned it in the unity editor

  • @cqrhqr3418
    @cqrhqr3418 4 місяці тому

    sero izlendi

  • @Jay_BanZ
    @Jay_BanZ Рік тому +1

    okay so im trynna do like an open locker door thing but when i make the animator do the open animation it goes okay, but when i try to close it, it still tries to open it even if its already open (i know this bc i also but a debug.log statment telling me if the door is opened and it always comes back as opened) so is there any solution to this?

  • @toto3777
    @toto3777 Рік тому +1

    Didn't work.

  • @JoshuaAguilar-fc6np
    @JoshuaAguilar-fc6np Рік тому +2

    Thank you very much! Was struggling handling interactions, and you just solved one of my main problems.

  • @justawhisp4160
    @justawhisp4160 Місяць тому

    tysm why aren't all tutorials like this
    also, to anyone stuck, the problem I had before I got it working was the interactor source should be the camera the script is on and the interactable object's collider needs to have "is trigger" checked.

  • @hoangbach5175
    @hoangbach5175 4 місяці тому

    Can i ask how to make it work in one script, i has disable the first script then when i use the second one, it active the first one even the first one is disable, when i private the Interact function it become error, thanks

  • @brage2
    @brage2 Рік тому +1

    If I add multiple Interactions to my Object it only executes the first in the component hirachie. Is there a way to execute all, cause I want to reuse these scripts on other objects say a sign and a note can both use text being shown on interaction.

    • @cheetamcu644
      @cheetamcu644 Рік тому +1

      Would need more context to this, but I'm pretty sure you would just merge the interactions to one script? (I don't fully understand what your saying). I'm just throwing out a guess by the way I am still pretty new to C#, but understand programming logic so I could figure it out if I saw the actual code and was given time to tinker.

    • @AliAlBrrak
      @AliAlBrrak 7 місяців тому

      I'm 7 months late but Unity has GetComponents() with an s
      It returns a list that you can loop over

  • @Auck130
    @Auck130 2 місяці тому

    my code just says error and tells me that the interactorSource is empty

  • @MalicProductions
    @MalicProductions 10 місяців тому +1

    Worked perfectly for my purposes. Thanks.

  • @DolphLOL
    @DolphLOL Рік тому +1

    Why exactly did we add the interface?

    • @Rytech_Dev
      @Rytech_Dev  Рік тому +5

      So you can have multiple different classes be unified under one reference. For instance, you can have two classes like "door" and "chair" and you wouldn't have to check for two components if you can just get the interface as a component.

    • @DolphLOL
      @DolphLOL Рік тому

      @@Rytech_Dev ty

  • @thescribblersdiary
    @thescribblersdiary Місяць тому

    Thanks man! Great knowledge

  • @somestuff3872
    @somestuff3872 Рік тому +1

    Sir. For this you got my sub

  • @DevilDrinksTea
    @DevilDrinksTea Рік тому +1

    Super helpful, thank you

  • @sebastianbramborak2756
    @sebastianbramborak2756 10 місяців тому

    Trying to add script to MainCamera and it says this, any ideas?
    "Can't add script behaviour 'Interactor'. The script class can't be abstract!"

    • @sebastianbramborak2756
      @sebastianbramborak2756 10 місяців тому +1

      Fixed! In case someone have same error as me, check "public class Interactor : MonoBehaviour", that you have same name of script as in script (in my case "Interactor")

  • @ethanBBB
    @ethanBBB 10 місяців тому

    I'm having an issue and I cant figure out why, I have the raycast script and everything and it was working and then I made a new object and tested the number generator on it and it wouldnt work but the original objects did anyone know why?

    • @Legionope
      @Legionope 4 місяці тому

      Two problems that are frequently re-occurring are:
      1. The raycast is being blocked by text or an image on your canvas. To solve it, you either need to put those on a different layer or uncheck their raycast option. (This also counts for textmeshPro)
      2. You use cursor lock mode and by default, Unity thought it was a good idea to lock your actual invisible cursor to a position of 0,0 (Upper left of your screen) instead of in the middle. In later versions of Unity's Input System they've added a dropdown option where you can lock the cursor and have it be in the middle.

  • @Endercraft-kf3tk
    @Endercraft-kf3tk 10 місяців тому

    How would you put a countdow timer into this system?

  • @AcedGamedev
    @AcedGamedev Рік тому +1

    Thanks man, helped out a LOT with my game!

  • @varcel4625
    @varcel4625 4 місяці тому

    Extremely well made tutorial! Keep up the work!

  • @black_squall
    @black_squall 10 місяців тому

    I kinda like these shawty tutorials

  • @isacsimoes_
    @isacsimoes_ Рік тому +1

    Wow great video loved it.

  • @PugVRYT_Official
    @PugVRYT_Official Рік тому

    I don’t have some of the buttons for the script

  • @JunaBot
    @JunaBot 11 місяців тому

    version mobile?

  • @Grizzdrop
    @Grizzdrop Рік тому

    I am getting errors about script class not being found when I try to add the script. any advice?

    • @yash_dhiman-tw8nh
      @yash_dhiman-tw8nh 6 місяців тому

      Verify that the script name in Unity matches the one in Visual Studio; a discrepancy here could be the issue. The script names must be identical in both Unity and Visual Studio.

  • @DeveloperOfReality
    @DeveloperOfReality Рік тому

    I seem to be having an issue where Unity is telling me that InteractorSource.Position doesn't exist (at what should be line 22), could someone give me some pointers?

    • @bluejay7071
      @bluejay7071 9 місяців тому +1

      What did you declare as the InteractorSource? It should be the camera. Make sure it is set as the camera in the inspector.

    • @thewaterwasfine
      @thewaterwasfine 9 місяців тому

      @@bluejay7071 ty. this was exactly the answer i was looking for as well

  • @lettuce1355
    @lettuce1355 Рік тому

    Can this be used in mobile? Thank you

    • @MysticMaverick0639
      @MysticMaverick0639 10 місяців тому

      instead of Input.GetKeyDown, do GetMouseButtonDown(0)) and it will work as a tap on mobile.

  • @imwatchingasalways
    @imwatchingasalways Рік тому +2

    i just got back into coding and i used ur tutorial for picking up items, but I cant figure out how to make it to where the object faces the camera. Can anyone help?

    • @theodore6432
      @theodore6432 Рік тому +1

      Ik this is late, but maybe you could have the item, upon using the interact function, will find the camera object and copy it's rotation? Maybe you could also lerp the rotation from what it was to what you want it to be to make it smoother.

  • @lucianbodnaresku6568
    @lucianbodnaresku6568 Рік тому

    Really helpfull tysm

  • @brage2
    @brage2 Рік тому

    Suppose I use a coroutine with a WaitUntil that waits until F is pressed in my Interact. In that case, it will still execute when I am no longer looking at the object [which makes sense], any ideas on how I "cancel" the Interaction or the Coroutine after it´s started? Because I don´t want to do the whole ray-checking thing in my Interact scripts, as that would kinda defeat the purpose of the interface and would bloat scripts.

    • @hyperDev_
      @hyperDev_ 8 місяців тому

      use stuff like 'return;' or hows called. im not sure but i think it works

  • @legosol1081
    @legosol1081 Рік тому

    thank you very much!!

  • @Deleted328
    @Deleted328 Рік тому

    wohhhoa

  • @emeraldwas9k
    @emeraldwas9k Рік тому

    Thanks :D

  • @maucazalv903
    @maucazalv903 Рік тому

    can I use it for a 3d person game?

    • @s-ata-n
      @s-ata-n Рік тому +1

      do you mean third person?

    • @maucazalv903
      @maucazalv903 Рік тому

      @@s-ata-n yes

    • @s-ata-n
      @s-ata-n Рік тому +1

      @@maucazalv903 İ dont know the anwser just wanted to be sure. lol

    • @JackDylanDaniels
      @JackDylanDaniels Рік тому +1

      yep im using it right now

  • @Maskeowl
    @Maskeowl 10 місяців тому +1

    WHATTA HEK BRO İ HATE WACH
    İNG OTHER TTORAL SHT AFTER SEENİNG THİS

  • @thev01d12
    @thev01d12 Рік тому

    How did you do that effect where the coin from world position went to the coin ui position