Search Unity

Question Need Help With My Sleep Script Please.

Discussion in 'Scripting' started by metaldc4life, Jul 25, 2022.

  1. metaldc4life

    metaldc4life

    Joined:
    Sep 26, 2014
    Posts:
    179
    Hello, I am trying to recreate a game based very loosely around the stalker series and i need help with this one script pertaining to a sleep system..

    So far, I have this: I created a cube and marked it as trigger and whilst entering the trigger the text "press e to sleep" works. (that much i did yay!)

    Code (CSharp):
    1. using System.Collections;
    2.      using System.Collections.Generic;
    3.      using UnityEngine;
    4.    
    5.      public class Sleep : MonoBehaviour
    6.      {
    7.          public float timer = 0;
    8.          public float timerMax = 0;
    9.          public Font font;
    10.          bool inZone;
    11.        
    12.          
    13.          void Update ()
    14.          {
    15.            
    16.              //if(!Waited(3)) return;
    17.          
    18.          }
    19.    
    20.          void OnTriggerStay(Collider other) {
    21.              if (other.CompareTag ("Player")) {
    22.                  inZone = true;
    23.                  if (Input.GetKeyDown (KeyCode.E)) {
    24.                  }
    25.              }
    26.          }
    27.          void OnTriggerExit(Collider other) {
    28.              if (other.CompareTag ("Player")) {
    29.                  inZone = false;
    30.              }
    31.          }
    32.        
    33.          void OnGUI(){
    34.              if (inZone) {
    35.                  GUIStyle style = new GUIStyle ();
    36.                  style.font = font;
    37.                  style.fontSize = 35;
    38.                  style.normal.textColor = Color.white;
    39.                  Rect rect = new Rect (Screen.width / 2 - 50, Screen.height / 2 - 22.5f, 200, 45);
    40.                  GUI.Label (rect, "Press E To Sleep", style);
    41.              }
    42.            
    43.          }
    44.      }
    but what i want to achieve is when i enter a collider VIA trigger (while hitting "e" once) the player will sleep for a designated time..

    Here are the scripts i am using and I would really appreciate the help a lot as I am trying my hardest to code my own stuff.. (Please go easy on me too..)

    here is the day script i want to integrate with this system:

    Code (CSharp):
    1. using System.Collections;
    2.      using UnityEngine;
    3.    
    4.    
    5.          public class TheTimeOfDay : MonoBehaviour
    6.          {
    7.        
    8.    
    9.              /// <summary></summary>
    10.              public float NormalizedTime { get { return m_NormalizedTime; } set { m_NormalizedTime = float.IsNaN(Mathf.Repeat(value, 1f)) ? 0f : Mathf.Repeat(value, 1f); m_CurrentHour = (int)(m_NormalizedTime * 24f);} }
    11.    
    12.              /// <summary></summary>
    13.              public int CurrentHour { get { return m_CurrentHour; } }
    14.    
    15.              [Header("Setup")]
    16.    
    17.              [SerializeField]
    18.              private Light m_Sun;
    19.    
    20.              [SerializeField]
    21.              private Light m_Moon;
    22.    
    23.              [Header("General")]
    24.    
    25.              [SerializeField]
    26.              private bool m_StopTime;
    27.    
    28.              [SerializeField]
    29.              private bool m_ShowGUI;
    30.    
    31.              [SerializeField]
    32.              [Range(0, 24)]
    33.              [Tooltip("The current hour (00:00 AM to 12:00 PM to 24:00 PM)")]
    34.              private int m_CurrentHour = 6;
    35.    
    36.              [SerializeField]
    37.              [Tooltip("How many seconds are in a day.")]
    38.              private int m_DayDuration = 900;
    39.    
    40.              [SerializeField]
    41.              [Tooltip("On which axis should the moon and sun rotate?")]
    42.              private Vector3 m_RotationAxis = Vector2.right;
    43.    
    44.              [Header("Fog")]
    45.    
    46.              [SerializeField]
    47.              private FogMode m_FogMode = FogMode.ExponentialSquared;
    48.    
    49.              [SerializeField]
    50.              [Tooltip("Fog intensity variation over the whole day & night cycle.")]
    51.              private AnimationCurve m_FogIntensity;
    52.    
    53.              [SerializeField]
    54.              [Tooltip("Fog color variation over the whole day & night cycle.")]
    55.              private Gradient m_FogColor;
    56.    
    57.              [Header("Sun")]
    58.    
    59.              [SerializeField]
    60.              [Tooltip("Sun intensity variation over the whole day & night cycle.")]
    61.              private AnimationCurve m_SunIntensity;
    62.    
    63.              [SerializeField]
    64.              [Tooltip("Sun color variation over the whole day & night cycle.")]
    65.              private Gradient m_SunColor;
    66.    
    67.              [Header("Moon")]
    68.    
    69.              [SerializeField]
    70.              [Tooltip("Moon intensity variation over the whole day & night cycle.")]
    71.              private AnimationCurve m_MoonIntensity;
    72.    
    73.              [SerializeField]
    74.              [Tooltip("Moon color variation over the whole day & night cycle.")]
    75.              private Gradient m_MoonColor;
    76.    
    77.              [Header("Skybox")]
    78.    
    79.              [SerializeField]
    80.              private Material m_Skybox;
    81.    
    82.              [SerializeField]
    83.              private AnimationCurve m_SkyboxBlend;
    84.    
    85.              private Transform m_SunTransform;
    86.              private Transform m_MoonTransform;
    87.              private float m_NormalizedTime;
    88.              private float m_TimeIncrement;
    89.        
    90.        
    91.              private void Awake()
    92.              {
    93.                  if(!m_Sun || !m_Moon)
    94.                  {
    95.                      Debug.LogError("The moon or sun are not assigned in the inspector! please assign them and restart the game.", this);
    96.                      enabled = false;
    97.                      return;
    98.                  }
    99.    
    100.                  m_SunTransform = m_Sun.transform;
    101.                  m_MoonTransform = m_Moon.transform;
    102.    
    103.                  AccommodateEditorChanges();
    104.    
    105.              }
    106.    
    107.              private void OnGUI()
    108.              {
    109.                  if(m_ShowGUI)
    110.                  {
    111.                      Rect rect = new Rect(8f, 8f, 128f, 20f);
    112.                      m_StopTime = GUI.Toggle(rect, m_StopTime, "Stop Time?");
    113.    
    114.                      // Manual time control
    115.                      string timeLabel = "Time: " + m_CurrentHour + " ";
    116.    
    117.                      rect.y = rect.yMax + 4f;
    118.                      GUI.Label(rect, timeLabel);
    119.    
    120.                      rect.y = rect.yMax;
    121.    
    122.                      if(m_StopTime)
    123.                          m_NormalizedTime = GUI.HorizontalSlider(rect, m_NormalizedTime, 0f, 1f);
    124.                      else
    125.                          GUI.HorizontalSlider(rect, m_NormalizedTime, 0f, 1f);
    126.    
    127.                      rect.y = rect.yMax;
    128.                      rect.width = 256f;
    129.                      GUI.Label(rect, "Day Duration: " + m_DayDuration + " seconds");
    130.    
    131.                      rect.y = rect.yMax;
    132.                      rect.width = 128f;
    133.                      m_DayDuration = (int)GUI.HorizontalSlider(rect, m_DayDuration, 0, 1000);
    134.    
    135.                      m_TimeIncrement = 1f / m_DayDuration;
    136.                  }
    137.              }
    138.    
    139.              private void Update()
    140.              {
    141.                  // Time loop.
    142.                  if(!m_StopTime)
    143.                      NormalizedTime += Time.deltaTime * m_TimeIncrement;
    144.    
    145.                  m_CurrentHour = (int)(NormalizedTime * 24f);
    146.    
    147.                  // Ambient light.
    148.                  RenderSettings.ambientIntensity = Mathf.Clamp01(m_Sun.intensity);
    149.    
    150.                  // Fog
    151.                  RenderSettings.fogDensity = m_FogIntensity.Evaluate(NormalizedTime);
    152.                  RenderSettings.fogColor = m_FogColor.Evaluate(NormalizedTime);
    153.    
    154.                  // Sun
    155.                  m_SunTransform.rotation = Quaternion.Euler(m_RotationAxis * (NormalizedTime * 360f - 90f));
    156.                  m_Sun.intensity = m_SunIntensity.Evaluate(NormalizedTime);
    157.                  m_Sun.color = m_SunColor.Evaluate(NormalizedTime);
    158.        
    159.                  m_Sun.enabled = m_Sun.intensity > 0f;
    160.    
    161.                  // Moon
    162.                  m_MoonTransform.rotation = Quaternion.Euler(-m_RotationAxis * (NormalizedTime * 360f - 90f));
    163.                  m_Moon.intensity = m_MoonIntensity.Evaluate(NormalizedTime);
    164.                  m_Moon.color = m_MoonColor.Evaluate(NormalizedTime);
    165.    
    166.                  m_Moon.enabled = m_Moon.intensity > 0f;
    167.    
    168.                  // Skybox
    169.                  if(m_Skybox)
    170.                      m_Skybox.SetFloat("_Blend", m_SkyboxBlend.Evaluate(m_NormalizedTime));
    171.    
    172.              }
    173.    
    174.              private void OnValidate()
    175.              {
    176.                  AccommodateEditorChanges();
    177.    
    178.                  m_SunTransform = m_Sun.transform;
    179.                  m_MoonTransform = m_Moon.transform;
    180.    
    181.                  Update();
    182.              }
    183.    
    184.              private void AccommodateEditorChanges()
    185.              {
    186.                  m_TimeIncrement = 1f / m_DayDuration;
    187.                  m_NormalizedTime = m_CurrentHour / 24f;
    188.    
    189.                  RenderSettings.fogMode = m_FogMode;
    190.              }
    191.          }
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,689
    There's no difference between sensing a "door opening" or "treasure chest opening" via trigger.

    Start with any one of the 2.667 million tutorials on opening doors and chests, and when you get it fully working, plumb the action of any keypress into your existing sleep code.

    Keep in mind the code will be a tiny fraction of the problem. There will be scene, prefab, collider, etc. setup that is absolutely critical to proper functionality of any system.
     
    metaldc4life likes this.
  3. metaldc4life

    metaldc4life

    Joined:
    Sep 26, 2014
    Posts:
    179
    Thank You For Your Reply, :)
    I am just starting to understand how functions function lol it's just a matter how to trigger them..
    (and where to put the code too)
    I have dyslexia pretty bad and I am having a hard time even typing let alone coding (hence the long reply heh)
    If you can give me some pointers on how i can go about doing this i'd be very grateful..

    Also i have heard of visual scripting, would you even recommend anything like that?

    Like Bolt?
     
  4. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,689
    Tutorials and example code are great, but keep this in mind to maximize your success and minimize your frustration:

    How to do tutorials properly, two (2) simple steps to success:

    Step 1. Follow the tutorial and do every single step of the tutorial 100% precisely the way it is shown. Even the slightest deviation (even a single character!) generally ends in disaster. That's how software engineering works. Every step must be taken, every single letter must be spelled, capitalized, punctuated and spaced (or not spaced) properly, literally NOTHING can be omitted or skipped.

    Fortunately this is the easiest part to get right: Be a robot. Don't make any mistakes.
    BE PERFECT IN EVERYTHING YOU DO HERE!!

    If you get any errors, learn how to read the error code and fix your error. Google is your friend here. Do NOT continue until you fix your error. Your error will probably be somewhere near the parenthesis numbers (line and character position) in the file. It is almost CERTAINLY your typo causing the error, so look again and fix it.

    Step 2. Go back and work through every part of the tutorial again, and this time explain it to your doggie. See how I am doing that in my avatar picture? If you have no dog, explain it to your house plant. If you are unable to explain any part of it, STOP. DO NOT PROCEED. Now go learn how that part works. Read the documentation on the functions involved. Go back to the tutorial and try to figure out WHY they did that. This is the part that takes a LOT of time when you are new. It might take days or weeks to work through a single 5-minute tutorial. Stick with it. You will learn.

    Step 2 is the part everybody seems to miss. Without Step 2 you are simply a code-typing monkey and outside of the specific tutorial you did, you will be completely lost. If you want to learn, you MUST do Step 2.

    Of course, all this presupposes no errors in the tutorial. For certain tutorial makers (like Unity, Brackeys, Imphenzia, Sebastian Lague) this is usually the case. For some other less-well-known content creators, this is less true. Read the comments on the video: did anyone have issues like you did? If there's an error, you will NEVER be the first guy to find it.

    Beyond that, Step 3, 4, 5 and 6 become easy because you already understand!

    I have not used Visual Scripting. You can see the forum here:

    https://forum.unity.com/forums/visual-scripting.537/

    The same rules of how to learn apply to Visual Scripting. The main difference is you cannot copy / paste snippets of code easily, but instead must reconstruct visual diagrams to replicate what a tutorial might tell you.
     
    metaldc4life likes this.
  5. metaldc4life

    metaldc4life

    Joined:
    Sep 26, 2014
    Posts:
    179
    Wow Thanks for all of the information you gave,
    It's much appreciated!
     
  6. metaldc4life

    metaldc4life

    Joined:
    Sep 26, 2014
    Posts:
    179
    I still cannot seem to get this to work..
    I don't mean to be a pain in the butt about it but i would like to finish it so i can move on to level design as i like to get all of the scripts working correctly how i want them before the level design...
    All i want is when i enter the cube to press "e" (which i have coded) and wait over a period of time (which i do not have yet)

    I'm sure it's easy but just need a little help on how to do this (I know it is triggers but what do i trigger???)

    Thank You Again!
     
  7. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,689
    The essence of waiting over a period of time is simple:

    - make a float "sleeping" variable;
    private float sleeping;


    - when you are in the cube trigger and press E, set it to the desired sleep time:

    Code (csharp):
    1. sleeping = 100; // sleep for 100 seconds.
    - now in your main player input Update() area, BEFORE you allow any input or movement:

    Code (csharp):
    1. if (sleeping > 0)
    2. {
    3.   Debug.Log( "Sleeping: you have " + sleeping + " seconds left.");
    4.   sleeping -= Time.deltaTime;
    5.   return;
    6. }
    Everything after that is just UI and presentation details.
     
    metaldc4life likes this.
  8. metaldc4life

    metaldc4life

    Joined:
    Sep 26, 2014
    Posts:
    179
    OMG Thank You!
    I really appreciate your help!
    You have opened many learning doors for me.. :D