Can someone help me with the interaction system

Guys i made a script for interaction and examine system but when i examine items ,the event that i want to happen is repeating, for example 7 times, if i press the f button 7 times (sry i dont know how to explain it)

here is the Interaction system script

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

public class InteractionSystem : MonoBehaviour
{
    [Header("Detection Fields")]
    public Transform detectionPoint;
    private const float detectionRadius = 0.5f;
    public LayerMask detectionLayer;
    public GameObject detectedObject;
    [Header("Examin Fields")]
    public GameObject examineWindow;
    public Image examineImage;
    public Text examineText;
    public bool isExaming;
    [Header("Others")]
    public List<GameObject> pickedItems=new List<GameObject>();

    void Update()
    {
        if(DetectObject())
        {
            if(InteractInput())
            {
                detectedObject.GetComponent<Item>().Interact();
            }
        }
    }

    private void OnDrawGizmosSelected()
    {
        Gizmos.color = Color.green;
        Gizmos.DrawSphere(detectionPoint.position, detectionRadius);
    }

    bool InteractInput()
    {
        return Input.GetKeyDown(KeyCode.F);
    }

    bool DetectObject()
    {
            Collider2D obj = Physics2D.OverlapCircle(detectionPoint.position,detectionRadius,detectionLayer);
       
        if(obj == null)
        {
            detectedObject = null;
            return false;
        }
        else
        {
            detectedObject = obj.gameObject;
            return true;
        }
    } 

    public void PickUpItem(GameObject item)
    {
        pickedItems.Add(item);
    }

    public void ExamineItem(Item item)
    {
        if(isExaming)
        {
            Debug.Log("Close");
            examineWindow.SetActive(false);
            isExaming = false;
        }
        else
        {
            Debug.Log("Examine");
            examineImage.sprite = item.GetComponent<SpriteRenderer>().sprite;
            examineText.text = item.descriptionText;
            examineWindow.SetActive(true);
            isExaming = true;
        }
    }
}

and this is the items script

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
[RequireComponent(typeof(BoxCollider2D))]
public class Item : MonoBehaviour
{
     public enum InteractionType { NONE, PickUp, Examine }
     public InteractionType type;
     [Header("Examine")]
     public string descriptionText;
     public UnityEvent customEvent;
     private void Reset()
     {
         GetComponent<Collider2D>().isTrigger = true;
         gameObject.layer = 10;
     }
     public void Interact()
     {
         switch(type)
         {
             case InteractionType.PickUp:
                 FindObjectOfType<InteractionSystem>().PickUpItem(gameObject);
                 gameObject.SetActive(false);
                     break;
             case InteractionType.Examine:
                 FindObjectOfType<InteractionSystem>().ExamineItem(this);
                     break;
             default:
                 Debug.Log("NULL ITEM");
                 break;
         }
         customEvent.Invoke();
 
     }
}

If I press “f” seven times then why shouldn’t I interact with an item seven times? Makes sense to me.

Maybe if you could describe more what you actually want it to do?

1 Like

i want to pull a lever and when i pull it i want to apear a key but i dont want it to apear multiple times

Then set a boolean flag to determine whether it’s been interacted with or not.

1 Like

i tried some variants but they didnt work .Can you tell me how to do it please

Time for you to start debugging! Remember, nobody here can do it for you. Here’s how to get started:

You must find a way to get the information you need in order to reason about what the problem is.

Once you understand what the problem is, you may begin to reason about a solution to the problem.

What is often happening in these cases is one of the following:

  • the code you think is executing is not actually executing at all
  • the code is executing far EARLIER or LATER than you think
  • the code is executing far LESS OFTEN than you think
  • the code is executing far MORE OFTEN than you think
  • the code is executing on another GameObject than you think it is
  • you’re getting an error or warning and you haven’t noticed it in the console window

To help gain more insight into your problem, I recommend liberally sprinkling Debug.Log() statements through your code to display information in realtime.

Doing this should help you answer these types of questions:

  • is this code even running? which parts are running? how often does it run? what order does it run in?
  • what are the values of the variables involved? Are they initialized? Are the values reasonable?
  • are you meeting ALL the requirements to receive callbacks such as triggers / colliders (review the documentation)

Knowing this information will help you reason about the behavior you are seeing.

You can also supply a second argument to Debug.Log() and when you click the message, it will highlight the object in scene, such as Debug.Log("Problem!",this);

If your problem would benefit from in-scene or in-game visualization, Debug.DrawRay() or Debug.DrawLine() can help you visualize things like rays (used in raycasting) or distances.

You can also call Debug.Break() to pause the Editor when certain interesting pieces of code run, and then study the scene manually, looking for all the parts, where they are, what scripts are on them, etc.

You can also call GameObject.CreatePrimitive() to emplace debug-marker-ish objects in the scene at runtime.

You could also just display various important quantities in UI Text elements to watch them change as you play the game.

If you are running a mobile device you can also view the console output. Google for how on your particular mobile target, such as this answer or iOS: https://discussions.unity.com/t/700551 or this answer for Android: https://discussions.unity.com/t/699654

If you are working in VR, it might be useful to make your on onscreen log output, or integrate one from the asset store, so you can see what is happening as you operate your software.

Another useful approach is to temporarily strip out everything besides what is necessary to prove your issue. This can simplify and isolate compounding effects of other items in your scene or prefab.

Here’s an example of putting in a laser-focused Debug.Log() and how that can save you a TON of time wallowing around speculating what might be going wrong:

https://discussions.unity.com/t/839300/3

When in doubt, print it out!™

Note: the print() function is an alias for Debug.Log() provided by the MonoBehaviour class.

The idea is essentially simple. You have a bool called alreadypressed or something like that. Set it to false, initially. When the player pulls the lever check alreadypressed. If already pressed is true then do nothing. If alreadypressed is false, then make the key appear and set alreadypressed to true so that nothing happens the next time that the player clicks.

1 Like

i tried like this :

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

public class InteractionSystem : MonoBehaviour
{
    [Header("Detection Fields")]
    public Transform detectionPoint;
    private const float detectionRadius = 0.5f;
    public LayerMask detectionLayer;
    public GameObject detectedObject;
    [Header("Examin Fields")]
    public GameObject examineWindow;
    public GameObject grabbedObject;
    public float grabbedObjectYValue;
    public Transform grabPoint;
    public Image examineImage;
    public Text examineText;
    public bool isExaming;
    public bool isGrabbing;
    bool alreadypressed = false;

    void Update()
    {
        if(DetectObject())
        {
            if(InteractInput())
            {
                detectedObject.GetComponent<Item>().Interact();
            }
        }
    }

    private void OnDrawGizmosSelected()
    {
        Gizmos.color = Color.green;
        Gizmos.DrawSphere(detectionPoint.position, detectionRadius);
    }

    bool InteractInput()
    {
        return Input.GetKeyDown(KeyCode.F);
    }

    bool DetectObject()
    {
            Collider2D obj = Physics2D.OverlapCircle(detectionPoint.position,detectionRadius,detectionLayer);
     
        if(obj == null)
        {
            detectedObject = null;
            return false;
        }
        else
        {
            detectedObject = obj.gameObject;
            return true;
        }
    }

    public void GrabDrop()
    {
        if (isGrabbing)
        {
            isGrabbing = false;
            grabbedObject.transform.parent = null;
            grabbedObject.transform.position =
                new Vector3(grabbedObject.transform.position.x, grabbedObjectYValue, grabbedObject.transform.position.z);
            grabbedObject = null;
        }
        else
        {
            isGrabbing = true;
            grabbedObject = detectedObject;
            grabbedObject.transform.parent = transform;
            grabbedObjectYValue = grabbedObject.transform.position.y;                               
            grabbedObject.transform.localPosition = grabPoint.localPosition;
        }
    }

    void FixedUpdate()
    {
        if (!alreadypressed)
        {
            ExamineItem(Item item); // I added (Item item) to try to see if its gonna work but there is a misstake even without (Item item)
        }
        else
            return;

    }


    public void ExamineItem(Item item)
    {
        if(isExaming)
        {
            Debug.Log("Close");
            examineWindow.SetActive(false);
            isExaming = false;
        }
        else
        {
            Debug.Log("Examine");
            examineImage.sprite = item.GetComponent<SpriteRenderer>().sprite;
            examineText.text = item.descriptionText;
            examineWindow.SetActive(true);
            isExaming = true;
         
        }
    }
}

but it just dont work

You’re never setting alreadyPressed to true. :slight_smile:

Consider doing that in the ExamineItem method.

1 Like

yea u r right but it sends me this error if there is (Item item) :
Assets\Scripts\InteractionSystem.cs(86,30): error CS1003: Syntax error, ‘,’ expected

and when ithere is not (Item item) :
Scripts\InteractionSystem.cs(86,13): error CS7036: There is no argument given that corresponds to the required formal parameter ‘item’ of ‘InteractionSystem.ExamineItem(Item)’

These are just typos. You can fix them yourself. Here’s how:

Remember: NOBODY here memorizes error codes. That’s not a thing. The error code is absolutely the least useful part of the error. It serves no purpose at all. Forget the error code. Put it out of your mind.

The complete error message contains everything you need to know to fix the error yourself.

The important parts of the error message are:

  • the description of the error itself (google this; you are NEVER the first one!)
  • the file it occurred in (critical!)
  • the line number and character position (the two numbers in parentheses)
  • also possibly useful is the stack trace (all the lines of text in the lower console window)

Always start with the FIRST error in the console window, as sometimes that error causes or compounds some or all of the subsequent errors. Often the error will be immediately prior to the indicated line, so make sure to check there as well.

Look in the documentation. Every API you attempt to use is probably documented somewhere. Are you using it correctly? Are you spelling it correctly?

All of that information is in the actual error message and you must pay attention to it. Learn how to identify it instantly so you don’t have to stop your progress and fiddle around with the forum.