Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

How i can add "wait until u can chop again" to my tree chopping script ?

Discussion in 'Scripting' started by faltegie57, Jan 28, 2016.

  1. faltegie57

    faltegie57

    Joined:
    Jan 28, 2016
    Posts:
    3
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class chopping : MonoBehaviour {
    5.     public Camera myCamera;
    6.     public int Tree_HP=10;
    7.     void Update ()
    8.     {
    9.         if (Tree_HP > 0) {
    10.             if (Vector3.Distance (transform.position, myCamera.transform.root.transform.position) < 5f) {
    11.                 if (Input.GetKeyDown(KeyCode.Mouse0)) {
    12.                     Ray ray = new Ray (myCamera.transform.position, myCamera.transform.forward);
    13.                     RaycastHit hit;
    14.                     if (Physics.Raycast (ray, out hit, 5f)) {
    15.                         if (hit.collider.gameObject == gameObject) {
    16.                             Tree_HP--;
    17.                             GetComponent<AudioSource>().Play();
    18.  
    19.  
    20.                         }
    21.                     }
    22.                 }
    23.             }
    24.         }
    25.         if (Tree_HP <= 0) {
    26.             Tree_HP = 0;
    27.             Destroy (gameObject);
    28.         }
    29.     }
    30. }
    31.  
    32.  
    33.    
    34.  
     
  2. KelsoMRK

    KelsoMRK

    Joined:
    Jul 18, 2010
    Posts:
    5,539
    Code (csharp):
    1.  
    2. float chopWait = 5; // chop every 5 seconds
    3. float lastChopTime; // last time we chopped
    4.  
    5. void Update()
    6. {
    7.     if (Tree_HP > 0 && Time.time - lastChopTime >= chopWait)
    8.     {
    9.         //....
    10.         if (Physics.Raycast(.....))
    11.         {
    12.             lastChopTime = Time.time;
    13.             Tree_HP--;
    14.              //.......
    15.         }
    16.     }
    17. }
    18.  
     
    Last edited: Jan 28, 2016
  3. faltegie57

    faltegie57

    Joined:
    Jan 28, 2016
    Posts:
    3
    There is problem with Time.Time
     
  4. faltegie57

    faltegie57

    Joined:
    Jan 28, 2016
    Posts:
    3
    There should be lastChopTime = Time.time;
    + Thanks :) it's working
     
  5. KelsoMRK

    KelsoMRK

    Joined:
    Jul 18, 2010
    Posts:
    5,539
    You're right - edited my original post.