Search Unity

Question Calculate how much time I spent looking at an object

Discussion in 'Scripting' started by joaogomes1298, Apr 13, 2021.

  1. joaogomes1298

    joaogomes1298

    Joined:
    Nov 20, 2019
    Posts:
    8
    So, the main idea is that I want to calculate dwell in my project. For that, I need to know the time when the player starts looking at an object and when he stopped looking at it, and calculate the difference. I am currently using the Raycasts approach, but I don't know how to specify "when you start looking" and "when you stop looking" since Raycast and RaycastHit are done in the Update method. Any idea on how to do this?
     
  2. lordofduct

    lordofduct

    Joined:
    Oct 3, 2011
    Posts:
    8,537
    joaogomes1298 likes this.
  3. joaogomes1298

    joaogomes1298

    Joined:
    Nov 20, 2019
    Posts:
    8
    Hey, sorry for only answering now, but I saw your solution yesterday and got a little overwhelmed by it. However, after taking a closer look at it, I have implemented a similar solution and it is working perfectly. Thanks a lot!
     
  4. CMDR_Garbage

    CMDR_Garbage

    Joined:
    Apr 29, 2019
    Posts:
    22
    Good thing you've found a solution,
    I would like to add another one:

    if you specifically need to check if it's within screen boundaries, Unity has functions called onBecomeVisible and onBecomeInvisible. With this you could make something like:

    Code (CSharp):
    1. bool isTiming;
    2.     float timer;
    3.  
    4.     public void OnBecameInvisible()
    5.     {
    6.         isTiming = false;
    7.         //do stuff with timer value
    8.     }
    9.  
    10.     public void OnBecameVisible()
    11.     {
    12.         timer = 0;
    13.         isTiming = true;
    14.     }
    15.  
    16.     private void Update()
    17.     {
    18.         if(isTiming)
    19.         {
    20.             timer += Time.deltaTime;
    21.         }
    22.     }
    Edit: if your object is casting shadows in camera view it will still count as visible as to render those shadows. Something to keep in mind ^^