Search Unity

I have tried to Implement a delay several times and have failed, can anyone help me?

Discussion in 'Scripting' started by jackhengen, Jul 5, 2019.

  1. jackhengen

    jackhengen

    Joined:
    Jun 30, 2019
    Posts:
    4
    First I made it so if a boolean was false and you clicked "r" it would make you dash and set the boolean true then set the boolean to true and invoke the boolean being set to false so you could dash again. This did not work. Then someone told me something about Coroutines but I looked into it and it looked very complicated so I waited and recieved another answer telling me to use Time.time. I tried this but it kept saying Time.time cannot be used in a monobehavior so I made a new class on my movement script called "dash"
    Code (CSharp):
    1. public class Dash
    2. {
    3.     public Transform player;
    4.     public Vector3 transportVector;
    5.     float now = Time.time;
    6.     float teleportAvailableAt;
    7.  
    8.     void FixedUpdate()
    9.     {
    10.         if (Input.GetKey("r"))
    11.         {
    12.             if (now >= teleportAvailableAt)
    13.                 player.position += transportVector;
    14.             teleportAvailableAt = now + 3f;
    15.         }
    16.  
    17.     }
    18. }
    now it is telling me "Object reference not set to instance of an object" can anyone please help me? I would really appreciate it. Thanks.j
     
  2. grizzly

    grizzly

    Joined:
    Dec 5, 2012
    Posts:
    357
    Time.time is variable so you'll need to continually check it. Also, FixedUpdate is for physics calculations, use Update instead.
    Code (CSharp):
    1. void Update()
    2. {
    3.     if (Input.GetKey("r"))
    4.     {
    5.         var now = Time.time;
    6.         if (now >= teleportAvailableAt)
    7.         {
    8.             player.position += transportVector;
    9.             teleportAvailableAt = now + 3f;
    10.         }
    11.     }
    12. }
    Make sure you've assigned a player to the field in the Inspector.
     
  3. karl_jones

    karl_jones

    Unity Technologies

    Joined:
    May 5, 2015
    Posts:
    8,279
  4. jackhengen

    jackhengen

    Joined:
    Jun 30, 2019
    Posts:
    4
    Thank you, this worked perfectly.