Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Tree falling and finally chop tree

Discussion in 'Scripting' started by Frientor, Feb 13, 2016.

  1. Frientor

    Frientor

    Joined:
    Oct 5, 2013
    Posts:
    47
    Hello,
    where do I find script for Tree falling .... Use Axe ---> Tree Fall ----> on the ground chop tree ---> Logs

    Health Tree.png Tree (Cut).png Tree Logs.png
     
  2. Frientor

    Frientor

    Joined:
    Oct 5, 2013
    Posts:
    47
    I use script for Tree Falling, but I miss the script that I could that tree on the ground cut
    for example
    The tree has 10 life when a tree falls 5 Life And Then on the ground cut
     
    Last edited: Feb 14, 2016
  3. Frientor

    Frientor

    Joined:
    Oct 5, 2013
    Posts:
    47
    this is example
     
  4. surya91

    surya91

    Joined:
    Feb 6, 2016
    Posts:
    8
    did you get the script now?

    i have try to write the script, but it still simple without equipment, only use left click (mouse) 4 - 5 times, it fall. but it still have little bit problem. i has fix it. and it success, but defending on the tree, if have 2 parts, it may use 2 script. on the script you can see . its for 1 part tree, i'll update it soon because i'm success to make it fall without push. the script not included with spawn tree. but i hope it help. you can see the example here. http://forum.unity3d.com/threads/tree-fall-problem-script.385978/
     
  5. Frientor

    Frientor

    Joined:
    Oct 5, 2013
    Posts:
    47
    I have script for Falling tree, but i haven´t script for Cut tree on the ground :/
     
  6. surya91

    surya91

    Joined:
    Feb 6, 2016
    Posts:
    8
    can i see your script? it may help me and you :D

    do your script use destroy object after it falling to the ground?

    maybe some code like RayCastHit can do this?
     
  7. Frientor

    Frientor

    Joined:
    Oct 5, 2013
    Posts:
    47
    I need a script when the tree falls, so that I could cut down on the ground, as in the video

    Fallen Tree script
    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. public class FallenTree : MonoBehaviour
    4. {
    5.     public float MinimumWeight;
    6.     public float MaximumWeight;
    7.     public float Damage;
    8.     // Will be assigned based on our wood cutting skill
    9.     public float Quality;
    10.  
    11.     // Use this for initialization
    12.     private void Start()
    13.     {
    14.     }
    15.  
    16.     // Update is called once per frame
    17.     private void Update()
    18.     {
    19.     }
    20. }
    Axe chop

    Code (CSharp):
    1. using System.Collections.Generic;
    2. using UnityEngine;
    3.  
    4. public class AxeChop : MonoBehaviour
    5. {
    6.     public int ChopPower;
    7.     public GameObject ChoppingWoodChips;
    8.     public GameObject[] FallingTreePrefab;
    9.     public GameObject Impact;
    10.  
    11.  
    12.     private int m_ChopDamage;
    13.     private int m_CurrentChoppingTreeIndex = -1;
    14.     // Use this for initialization
    15.     private void Start()
    16.     {
    17.     }
    18.  
    19.     // Update is called once per frame
    20.     private void Update()
    21.     {
    22.         if (Input.GetMouseButton(0))
    23.         {
    24.             GetComponent<Animation>().Play("PickAnimation");
    25.         }
    26.     }
    27.  
    28.     public void TreeChop()
    29.     {
    30.         // Did we click/attack something?
    31.  
    32.         RaycastHit hit;
    33.         // This ray will see what is where we clicked er chopped
    34.         var impactOnScreenPosition = Camera.main.WorldToScreenPoint(Impact.transform.position);
    35.  
    36.         Ray ray = Camera.main.ScreenPointToRay(impactOnScreenPosition);
    37.            
    38.  
    39.         // Did we hit anything within 10 units?);)
    40.         if (Physics.Raycast(ray, out hit, 10.0f))
    41.         {
    42.             // Did we even click er chop on the terrain/tree?);
    43.             if (hit.collider.name != Terrain.activeTerrain.name)
    44.             {
    45.                 // We didn't hit any part of the terrain (like a tree)
    46.                 return;
    47.             }
    48.  
    49.             // We hit the "terrain"! Now, how high is the ground at that point?
    50.             float sampleHeight = Terrain.activeTerrain.SampleHeight(hit.point);
    51.  
    52.             // If the height of the exact point we clicked/chopped at or below ground level, all we did
    53.             // was chop dirt.
    54.             if (hit.point.y <= sampleHeight + 0.01f)
    55.             {
    56.                 return;
    57.             }
    58.             // We must have clicked a tree! Chop it.
    59.             // Get the tree prototype index we hit, also.
    60.             int protoTypeIndex = ChopTree(hit);
    61.             if (protoTypeIndex == -1)
    62.             {
    63.                 // We haven't chopped enough for it to fall.
    64.                 return;
    65.             }
    66.             GameObject protoTypePrefab = Terrain.activeTerrain.terrainData.treePrototypes[protoTypeIndex].prefab;
    67.            
    68.             var fallenTreeScript = protoTypePrefab.GetComponent<FallenTree>();
    69.         }
    70.     }
    71.  
    72.     // Chops down the tree at hit location, and returns the prototype index
    73.     // With some changes, this could be refactored to return the selected (or chopped) tree, and
    74.     // then either display tree data to the player, or chop it.
    75.     // The return value is the tree slot index of the tree, it is -1 if we haven't chopped the tree down yet.
    76.     private int ChopTree(RaycastHit hit)
    77.     {
    78.         TerrainData terrain = Terrain.activeTerrain.terrainData;
    79.         TreeInstance[] treeInstances = terrain.treeInstances;
    80.  
    81.         // Our current closest tree initializes to far away
    82.         float maxDistance = float.MaxValue;
    83.         // Track our closest tree's position
    84.         var closestTreePosition = new Vector3();
    85.         // Let's find the closest tree to the place we chopped and hit something
    86.         int closestTreeIndex = 0;
    87.         var closestTree = new TreeInstance();
    88.         for (int i = 0; i < treeInstances.Length; i++)
    89.         {
    90.             TreeInstance currentTree = treeInstances[i];
    91.             // The the actual world position of the current tree we are checking
    92.             Vector3 currentTreeWorldPosition = Vector3.Scale(currentTree.position, terrain.size) +
    93.                                                Terrain.activeTerrain.transform.position;
    94.  
    95.             // Find the distance between the current tree and whatever we hit when chopping
    96.             float distance = Vector3.Distance(currentTreeWorldPosition, hit.point);
    97.  
    98.             // Is this tree even closer?
    99.             if (distance < maxDistance)
    100.             {
    101.                 maxDistance = distance;
    102.                 closestTreeIndex = i;
    103.                 closestTreePosition = currentTreeWorldPosition;
    104.                 closestTree = currentTree;
    105.             }
    106.         }
    107.  
    108.         // get the index of the closest tree..in the terrain tree slots, not the index of the tree in the whole terrain
    109.         int prototypeIndex = closestTree.prototypeIndex;
    110.  
    111.         // Play our chop shound
    112.         PlayChopSound(hit.point);
    113.  
    114.         if (m_CurrentChoppingTreeIndex != closestTreeIndex)
    115.         {
    116.             //This is a different tree we are chopping now, reset the damage!
    117.             // This means we can only chop on one tree at a time, switching trees sets their
    118.             // health back to full.
    119.             m_ChopDamage = ChopPower;
    120.             m_CurrentChoppingTreeIndex = closestTreeIndex;
    121.         }
    122.         else
    123.         {
    124.             // We are chopping on the same tree.
    125.             m_ChopDamage += ChopPower;
    126.         }
    127.  
    128.        
    129.         if (m_ChopDamage >= 100)
    130.         {
    131.             var treeInstancesToRemove = new List<TreeInstance>(terrain.treeInstances);
    132.             // We have chopped down this tree!
    133.             // Remove the tree from the terrain tree list
    134.             treeInstancesToRemove.RemoveAt(closestTreeIndex);
    135.             terrain.treeInstances = treeInstancesToRemove.ToArray();
    136.  
    137.             // Now refresh the terrain, getting rid of the darn collider
    138.             float[,] heights = terrain.GetHeights(0, 0, 0, 0);
    139.             terrain.SetHeights(0, 0, heights);
    140.  
    141.             // Put a falling tree in its place, tilted slightly away from the player
    142.             var fallingTree =
    143.                 (GameObject)
    144.                 Instantiate(FallingTreePrefab[prototypeIndex], closestTreePosition,
    145.                             Quaternion.AngleAxis(2, Vector3.right));
    146.             fallingTree.transform.localScale = new Vector3(closestTree.widthScale * fallingTree.transform.localScale.x,
    147.                                                            closestTree.heightScale * fallingTree.transform.localScale.y,
    148.                                                            closestTree.widthScale * fallingTree.transform.localScale.z);
    149.         }
    150.         return prototypeIndex;
    151.     }
    152.  
    153.     private void PlayChopSound(Vector3 point)
    154.     {
    155.         Instantiate(ChoppingWoodChips, point, Quaternion.identity);
    156.     }
    157. }
     
  8. Frientor

    Frientor

    Joined:
    Oct 5, 2013
    Posts:
    47
    Or this script is ... You Chopping tree ---> Tree Fall ----> You have logs...


    But this script is useless to me, I need that tree could still cut down on the ground
    TreeControler
    Code (JavaScript):
    1. #pragma strict
    2.  
    3. var treeHealth : int = 5;
    4.  
    5. var logs : Transform;
    6. var coconut : Transform;
    7. var tree : GameObject;
    8.  
    9. var speed : int = 8;
    10.  
    11. function Start()
    12. {
    13.     tree = this.gameObject;
    14.     GetComponent.<Rigidbody>().isKinematic = true;
    15. }
    16.  
    17. function Update()
    18. {
    19.     if(treeHealth <= 0)
    20.     {
    21.         GetComponent.<Rigidbody>().isKinematic = false;
    22.         GetComponent.<Rigidbody>().AddForce(transform.forward * speed);
    23.         DestroyTree();
    24.     }
    25. }
    26.  
    27. function DestroyTree()
    28. {
    29.     yield WaitForSeconds(7);
    30.  
    31.  
    32.     var position : Vector3 = Vector3(Random.Range(-1.0, 1.0), 0, Random.Range(-1.0, 1.0));
    33.     Instantiate(logs, tree.transform.position + Vector3(0,0,0) + position, Quaternion.identity);
    34.     Instantiate(logs, tree.transform.position + Vector3(2,2,0) + position, Quaternion.identity);
    35.     Instantiate(logs, tree.transform.position + Vector3(5,5,0) + position, Quaternion.identity);
    36.  
    37.     Instantiate(coconut, tree.transform.position + Vector3(0,0,0) + position, Quaternion.identity);
    38.     Instantiate(coconut, tree.transform.position + Vector3(2,2,0) + position, Quaternion.identity);
    39.     Instantiate(coconut, tree.transform.position + Vector3(5,5,0) + position, Quaternion.identity);
    40.  
    41. }
    42.  
    43.  
    44.  
    Raycast Tree
    Code (JavaScript):
    1. #pragma strict
    2.  
    3. var rayLength = 10;
    4.  
    5. private var treeScript : TreeController;
    6.  
    7. private var playerAnim : PlayerControl;
    8.  
    9. function Update()
    10. {
    11.     var hit : RaycastHit;
    12.     var fwd = transform.TransformDirection(Vector3.forward);
    13.  
    14.     if(Physics.Raycast(transform.position, fwd, hit, rayLength))
    15.     {
    16.         if(hit.collider.gameObject.tag == "Tree")
    17.         {
    18.             treeScript = GameObject.Find(hit.collider.gameObject.name).GetComponent(TreeController);
    19.             playerAnim = GameObject.Find("FPSArms_Axe@Idle").GetComponent(PlayerControl);
    20.          
    21.             if(Input.GetButtonDown("Fire1") && playerAnim.canSwing == true)
    22.             {
    23.                 treeScript.treeHealth -= 1;
    24.             }
    25.         }
    26.     }
    27. }
    28.  
     
  9. surya91

    surya91

    Joined:
    Feb 6, 2016
    Posts:
    8
    well i think we should make 2 health for the tree, first is before fall (your script have it) , the second is for falling tree.

    maybe like this, i can say the second variable for health of the falling tree on the ground is m_chopDamage2.

    so it may like this. (dont think it success, just try it )

    Code (CSharp):
    1.  if (m_ChopDamage >= 100)
    2.         {
    3.             var treeInstancesToRemove = new List<TreeInstance>(terrain.treeInstances);
    4.             // We have chopped down this tree!
    5.             // Remove the tree from the terrain tree list
    6.             treeInstancesToRemove.RemoveAt(closestTreeIndex);
    7.             terrain.treeInstances = treeInstancesToRemove.ToArray();
    8.             // Now refresh the terrain, getting rid of the darn collider
    9.             float[,] heights = terrain.GetHeights(0, 0, 0, 0);
    10.             terrain.SetHeights(0, 0, heights);
    11.             // Put a falling tree in its place, tilted slightly away from the player
    12.             var fallingTree =
    13.                 (GameObject)
    14.                 Instantiate(FallingTreePrefab[prototypeIndex], closestTreePosition,
    15.                             Quaternion.AngleAxis(2, Vector3.right));
    16.             fallingTree.transform.localScale = new Vector3(closestTree.widthScale * fallingTree.transform.localScale.x,
    17.                                                            closestTree.heightScale * fallingTree.transform.localScale.y,
    18.                                                            closestTree.widthScale * fallingTree.transform.localScale.z);
    19.         }
    20.         return prototypeIndex;
    21.     }
    22.  
    23. if(m_chopDamage2 >= 100) {
    24.             var treeInstancesToRemove = new List<TreeInstance>(terrain.treeInstances);
    25.             // We have chopped down this tree to get trunk!
    26.             // Remove the tree from the terrain tree list
    27.             treeInstancesToRemove.RemoveAt(closestTreeIndex);
    28.             terrain.treeInstances = treeInstancesToRemove.ToArray();
    29.             // Now refresh the terrain, getting rid of the darn collider
    30.             float[,] heights = terrain.GetHeights(0, 0, 0, 0);
    31.             terrain.SetHeights(0, 0, heights);
    32.             // Put a trunk in its place after falling tree chopped down
    33.             var TrunkTree =
    34.                 (GameObject)
    35.                 Instantiate(TrunkTreePrefab[prototypeIndex], closestTreePosition,
    36.                             Quaternion.AngleAxis(2, Vector3.right));
    37.            TrunkTree.transform.localScale = new Vector3(closestTree.widthScale * TrunkTree.transform.localScale.x,
    38.                                                            closestTree.heightScale * TrunkTree.transform.localScale.y,
    39.                                                            closestTree.widthScale * TrunkTree.transform.localScale.z);
    40.         }
    41.         return prototypeIndex;
    42.     }

    well falling tree changed into trunk. but it may drop on the same place.
    some kind like that, make 2 health (m_chopDown and m_chopDown2) and changes the falling tree into trunk. i'm not good at scripting, still learn, you may fix it with some idea :D, hope it help

    oh, try make it on new script. and put it on falling tree prefab. then you should have trunk prefab. how is it?
     
    Last edited: Feb 14, 2016
  10. Frientor

    Frientor

    Joined:
    Oct 5, 2013
    Posts:
    47
    somehow I do not want to take :D
     
  11. Frientor

    Frientor

    Joined:
    Oct 5, 2013
    Posts:
    47
    Ok its work... now?
    Now from fallen tree get Logs
    Fallen Tree ----> Cut Falen on the ground tree ----> Get Logs From Fallen Tree
    Code (CSharp):
    1. using System.Collections.Generic;
    2. using UnityEngine;
    3.  
    4. public class PickaxeChop : MonoBehaviour
    5. {
    6.     public int ChopPower;
    7.     public GameObject ChoppingWoodChips;
    8.     public GameObject[] FallingTreePrefab;
    9.     public GameObject[] TreeOnTheGroundPrefab;
    10.     public GameObject Impact;
    11.  
    12.  
    13.     private int m_ChopDamage;
    14.     private int m_ChopDamage2;
    15.     private int m_CurrentChoppingTreeIndex = -1;
    16.     // Use this for initialization
    17.     private void Start()
    18.     {
    19.     }
    20.  
    21.     // Update is called once per frame
    22.     private void Update()
    23.     {
    24.         if (Input.GetMouseButton(0))
    25.         {
    26.             GetComponent<Animation>().Play("PickAnimation");
    27.         }
    28.     }
    29.  
    30.     public void TreeChop()
    31.     {
    32.         // Did we click/attack something?
    33.  
    34.         RaycastHit hit;
    35.         // This ray will see what is where we clicked er chopped
    36.         var impactOnScreenPosition = Camera.main.WorldToScreenPoint(Impact.transform.position);
    37.  
    38.         Ray ray = Camera.main.ScreenPointToRay(impactOnScreenPosition);
    39.            
    40.  
    41.         // Did we hit anything within 10 units?);)
    42.         if (Physics.Raycast(ray, out hit, 10.0f))
    43.         {
    44.             // Did we even click er chop on the terrain/tree?);
    45.             if (hit.collider.name != Terrain.activeTerrain.name)
    46.             {
    47.                 // We didn't hit any part of the terrain (like a tree)
    48.                 return;
    49.             }
    50.  
    51.             // We hit the "terrain"! Now, how high is the ground at that point?
    52.             float sampleHeight = Terrain.activeTerrain.SampleHeight(hit.point);
    53.  
    54.             // If the height of the exact point we clicked/chopped at or below ground level, all we did
    55.             // was chop dirt.
    56.             if (hit.point.y <= sampleHeight + 0.01f)
    57.             {
    58.                 return;
    59.             }
    60.             // We must have clicked a tree! Chop it.
    61.             // Get the tree prototype index we hit, also.
    62.             int protoTypeIndex = ChopTree(hit);
    63.             if (protoTypeIndex == -1)
    64.             {
    65.                 // We haven't chopped enough for it to fall.
    66.                 return;
    67.             }
    68.             GameObject protoTypePrefab = Terrain.activeTerrain.terrainData.treePrototypes[protoTypeIndex].prefab;
    69.          
    70.             var fallenTreeScript = protoTypePrefab.GetComponent<FallenTree>();
    71.         }
    72.     }
    73.  
    74.     // Chops down the tree at hit location, and returns the prototype index
    75.     // With some changes, this could be refactored to return the selected (or chopped) tree, and
    76.     // then either display tree data to the player, or chop it.
    77.     // The return value is the tree slot index of the tree, it is -1 if we haven't chopped the tree down yet.
    78.     private int ChopTree(RaycastHit hit)
    79.     {
    80.         TerrainData terrain = Terrain.activeTerrain.terrainData;
    81.         TreeInstance[] treeInstances = terrain.treeInstances;
    82.  
    83.         // Our current closest tree initializes to far away
    84.         float maxDistance = float.MaxValue;
    85.         // Track our closest tree's position
    86.         var closestTreePosition = new Vector3();
    87.         // Let's find the closest tree to the place we chopped and hit something
    88.         int closestTreeIndex = 0;
    89.         var closestTree = new TreeInstance();
    90.         for (int i = 0; i < treeInstances.Length; i++)
    91.         {
    92.             TreeInstance currentTree = treeInstances[i];
    93.             // The the actual world position of the current tree we are checking
    94.             Vector3 currentTreeWorldPosition = Vector3.Scale(currentTree.position, terrain.size) +
    95.                                                Terrain.activeTerrain.transform.position;
    96.  
    97.             // Find the distance between the current tree and whatever we hit when chopping
    98.             float distance = Vector3.Distance(currentTreeWorldPosition, hit.point);
    99.  
    100.             // Is this tree even closer?
    101.             if (distance < maxDistance)
    102.             {
    103.                 maxDistance = distance;
    104.                 closestTreeIndex = i;
    105.                 closestTreePosition = currentTreeWorldPosition;
    106.                 closestTree = currentTree;
    107.             }
    108.         }
    109.  
    110.         // get the index of the closest tree..in the terrain tree slots, not the index of the tree in the whole terrain
    111.         int prototypeIndex = closestTree.prototypeIndex;
    112.  
    113.         // Play our chop shound
    114.         PlayChopSound(hit.point);
    115.  
    116.         if (m_CurrentChoppingTreeIndex != closestTreeIndex)
    117.         {
    118.             //This is a different tree we are chopping now, reset the damage!
    119.             // This means we can only chop on one tree at a time, switching trees sets their
    120.             // health back to full.
    121.             m_ChopDamage = ChopPower;
    122.             m_ChopDamage2 = ChopPower;
    123.             m_CurrentChoppingTreeIndex = closestTreeIndex;
    124.         }
    125.         else
    126.         {
    127.             // We are chopping on the same tree.
    128.             m_ChopDamage += ChopPower;
    129.             m_ChopDamage2 += ChopPower;
    130.         }
    131.  
    132.      
    133.      if (m_ChopDamage >= 100)
    134.             {
    135.                 var treeInstancesToRemove = new List<TreeInstance>(terrain.treeInstances);
    136.                 // We have chopped down this tree!
    137.                 // Remove the tree from the terrain tree list
    138.                 treeInstancesToRemove.RemoveAt(closestTreeIndex);
    139.                 terrain.treeInstances = treeInstancesToRemove.ToArray();
    140.                 // Now refresh the terrain, getting rid of the darn collider
    141.                 float[,] heights = terrain.GetHeights(0, 0, 0, 0);
    142.                 terrain.SetHeights(0, 0, heights);
    143.                 // Put a falling tree in its place, tilted slightly away from the player
    144.                 var fallingTree =
    145.                     (GameObject)
    146.                     Instantiate(FallingTreePrefab[prototypeIndex], closestTreePosition,
    147.                                 Quaternion.AngleAxis(2, Vector3.right));
    148.                 fallingTree.transform.localScale = new Vector3(closestTree.widthScale * fallingTree.transform.localScale.x,
    149.                                                                closestTree.heightScale * fallingTree.transform.localScale.y,
    150.                                                                closestTree.widthScale * fallingTree.transform.localScale.z);
    151.             }
    152.             return prototypeIndex;
    153.      
    154.    
    155.      if    (m_ChopDamage2 >= 100) {
    156.                 var treeInstancesToRemove = new List<TreeInstance>(terrain.treeInstances);
    157.                 // We have chopped down this tree to get logs!
    158.                 // Remove the tree from the terrain tree list
    159.                 treeInstancesToRemove.RemoveAt(closestTreeIndex);
    160.                 terrain.treeInstances = treeInstancesToRemove.ToArray();
    161.                 // Now refresh the terrain, getting rid of the darn collider
    162.                 float[,] heights = terrain.GetHeights(0, 0, 0, 0);
    163.                 terrain.SetHeights(0, 0, heights);
    164.                 // Put a trunk in its place after falling tree chopped down
    165.                 var TreeOnTheGround =
    166.                     (GameObject)
    167.                 Instantiate(TreeOnTheGroundPrefab[prototypeIndex], closestTreePosition,
    168.                                 Quaternion.AngleAxis(2, Vector3.right));
    169.             TreeOnTheGround.transform.localScale = new Vector3(closestTree.widthScale * TreeOnTheGround.transform.localScale.x,
    170.                                                                closestTree.heightScale * TreeOnTheGround.transform.localScale.y,
    171.                                                                closestTree.widthScale * TreeOnTheGround.transform.localScale.z);
    172.             }
    173.             return prototypeIndex;
    174.         }
    175.  
    176.  
    177.     private void PlayChopSound(Vector3 point)
    178.     {
    179.         Instantiate(ChoppingWoodChips, point, Quaternion.identity);
    180.     }
    181. }
     
  12. Frientor

    Frientor

    Joined:
    Oct 5, 2013
    Posts:
    47
    how this is put into the script?
    Quote: For fallen tree

    Example video:

    Chopping Tree ----> Tree Falling on the ground ----> Chop Fallen Tree on the Ground ---> Get Logs
    Code (CSharp):
    1.  
    2. using UnityEngine;
    3. using System.Collections;
    4.  
    5. public class MYCLASSNAME : MonoBehaviour {
    6.  
    7.  
    8. int treeHealth = 5;
    9.  
    10. Transform logs;
    11. Transform coconut;
    12. GameObject tree;
    13.  
    14. int speed = 8;
    15.  
    16. void  Start (){
    17.    tree = this.gameObject;
    18.    GetComponent.<Rigidbody>().isKinematic = true;
    19. }
    20.  
    21. void  Update (){
    22.    if(treeHealth <= 0)
    23.    {
    24.      GetComponent.<Rigidbody>().isKinematic = false;
    25.      GetComponent.<Rigidbody>().AddForce(transform.forward * speed);
    26.      DestroyTree();
    27.    }
    28. }
    29.  
    30. void  DestroyTree (){
    31.    yield return new WaitForSeconds(7);
    32.  
    33.  
    34.    Vector3 position = Vector3(Random.Range(-1.0f, 1.0f), 0, Random.Range(-1.0f, 1.0f));
    35.    Instantiate(logs, tree.transform.position + Vector3(0,0,0) + position, Quaternion.identity);
    36.    Instantiate(logs, tree.transform.position + Vector3(2,2,0) + position, Quaternion.identity);
    37.    Instantiate(logs, tree.transform.position + Vector3(5,5,0) + position, Quaternion.identity);
    38.  
    39.    Instantiate(coconut, tree.transform.position + Vector3(0,0,0) + position, Quaternion.identity);
    40.    Instantiate(coconut, tree.transform.position + Vector3(2,2,0) + position, Quaternion.identity);
    41.    Instantiate(coconut, tree.transform.position + Vector3(5,5,0) + position, Quaternion.identity);
    42.  
    43. }
    44.  
    45.  
    46.  
    47.  
    48. }
     
  13. surya91

    surya91

    Joined:
    Feb 6, 2016
    Posts:
    8
    first i want ask you, do you have that object(coconut and logs)?
    for tree you can use standard tree.
    well, i'm learning these script too, so i made some write, it dont finished and still have a bug i think. but it will work. i'm using C# to create these code.

    so like this, you need 3 prefab (object).

    1.tree : you should use Tag. see on inspector, click the tree and see inspector, if you dont find tree Tag, create new and Name it Tree (case sensitive).
    2.log
    3.coconut

    and the last important is your character, if you use standard asset character and if you see on herarchy, it will be like this FpsController > FirstPersonCharacter. (Unity 5)

    after that you need 2 script.

    1. treefall script, you have it up there. put it on the tree. but i recommend you use my script (C#) except you have the chop script with extension js too.
    2. chop script C# . put it on FirstPersonCharacter or Main Camera.

    the script you have is using unity 4. so it may still work or get some error. there may have API Updater, but if you fail. you can use my learning script :D
    on treefall script. you only need add a few more code to make it chop 2 times. so i think it will be like this, the first things you need to do create 2 new script (the C# Script), rename it to TreeController and RayCastChop. case sensitive.

    Code : TreeController Script.
    Note : if you change the name of script, you should change the public class TreeController too for make it work. actually after you create new script and rename it, it will change automatically, but if you save and rename it again, you should change it manually. for example, the name is TreeController. look the code.

    Code (CSharp):
    1.  
    2. using UnityEngine;
    3. using System.Collections;
    4.  
    5. public class TreeController : MonoBehaviour {
    6.  
    7.     public int treeHealth = 5;
    8.     public int fallHealth = 5; // this is new, because you need chop the tree again after fall. i am right? hehehe
    9.     public Transform logs;
    10.     public Transform coconut;
    11.     public GameObject tree;
    12.     public int speed = 8;
    13.     public Vector3 position;
    14.  
    15.     // Use this for initialization
    16.     void Start () {
    17.         tree = this.gameObject;
    18.         GetComponent<Rigidbody>().isKinematic = true;
    19.     }
    20.  
    21.     // Update is called once per frame
    22.     void Update () {
    23.         if (treeHealth <= 0) {
    24.             GetComponent<Rigidbody> ().isKinematic = false;
    25.             GetComponent<Rigidbody> ().AddForce (transform.forward * speed);
    26.             StartCoroutine(DestroyTree ()); // handle for time, or yield new wait for seconds. if not. your script (computer will      //be overloaded) LoL
    27.         }
    28.     }
    29.  
    30.     IEnumerator DestroyTree() { // IEnumerator is same with function (on JS) and void, but we need startCoroutine, so          //the script not overloaded.
    31.         yield return new WaitForSeconds (7); // if the tree has falling but still moving, change it to 6 - 1.
    32.         GetComponent<Rigidbody> ().isKinematic = true; // set it again so the tree will stop moving.
    33.  
    34.         if (fallHealth <= 0) { //after tree falling, we will wait the next chopping. so the tree will not gone before fall health 0
    35.             Destroy (tree);
    36.  
    37.             position = new Vector3 (Random.Range (-1.0f, 1.0f), 0, Random.Range (-1.0f, 1.0f));
    38.             Instantiate (logs, tree.transform.position + new Vector3 (0, 0, 0) + position, Quaternion.identity);
    39.             Instantiate (logs, tree.transform.position + new Vector3 (2, 2, 0) + position, Quaternion.identity);
    40.             Instantiate (logs, tree.transform.position + new Vector3 (5, 5, 0) + position, Quaternion.identity);
    41.  
    42.             Instantiate (coconut, tree.transform.position + new Vector3 (0, 0, 0) + position, Quaternion.identity);
    43.             Instantiate (coconut, tree.transform.position + new Vector3 (2, 2, 0) + position, Quaternion.identity);
    44.             Instantiate (coconut, tree.transform.position + new Vector3 (5, 5, 0) + position, Quaternion.identity);
    45.         }
    46.     }
    47. }
    48.  
    after that, put TreeController.cs on the tree u want, and remember to put these tree on scene. remember the tag too. you can see hierarcy for the tree, and see the script on inspector component. make sure the tree script has added. and you will see none(gameObject), then drag 3 object (tree you use or put on the scene, coconut and logs) in these script (none(gameObject)). put log on the logs. i hope you understand.
    now we make code for chop. and remember, i'm not best developer, i'm just a man who learn too. there may be best code in the world :D.


    Code : RayCastChop
    Code (CSharp):
    1.  
    2. using UnityEngine;
    3. using System.Collections;
    4.  
    5. public class RayCastChop : MonoBehaviour {
    6.  
    7.     public int rayLength = 10;
    8.     public Vector3 fwd;
    9.     private bool treeHasFalling = false; // we need to know if tree is falling or not yet falling.
    10.  
    11.     private TreeController treeScript; //defending on the name of your treeController Script up there, if you name it trees. then it //should named trees, and about treeScript after TreeController name, its a Variable. the name case sensitive.
    12.  
    13.     public RaycastHit hit;
    14.  
    15.     void start()
    16.     {
    17.     }
    18.  
    19.     void Update() {
    20.         fwd = transform.TransformDirection(Vector3.forward); // same as Vector3(0,0,1)
    21.  
    22.         if(Physics.Raycast(transform.position, fwd, out hit, rayLength))
    23.         {
    24.             if(hit.collider.gameObject.tag == "Tree") // the prefab or object tree must have a TAG, you can set it on the
    25.                 // inspector, but if you want the simple, and you dont know how to add TAG, change  code to this //(hit.collider.gameObject.name == "NameYourPrefabTree"); //the tree must have name, you can use hierarchy name or // best is prefab (object name). standard asset used treepalm.prefab hope you understand.
    26.                 // Tree Script.
    27.             {
    28.                 treeScript = GameObject.Find(hit.collider.gameObject.name).GetComponent<TreeController>();
    29.                 if(Input.GetKeyDown(KeyCode.Mouse0))
    30.                 {
    31.                     treeScript.treeHealth -= 1;
    32.                     StartCoroutine(waittree ());
    33.                 }
    34.             }
    35.         }
    36.  
    37.         if(Physics.Raycast(transform.position, fwd, out hit, rayLength) && treeHasFalling == true)
    38.         {
    39.             if(hit.collider.gameObject.tag == "Tree"); // same tree, but has falling.
    40.             {
    41.                 treeScript = GameObject.Find(hit.collider.gameObject.name).GetComponent<TreeController>();
    42.                 if(Input.GetKeyDown(KeyCode.Mouse0))
    43.                 {
    44.                     treeScript.fallHealth -= 1; //here is the second code after tree falling. you will chop it again to make lumber
    45.                 }
    46.             }
    47.         }
    48.     }
    49.  
    50.     IEnumerator waittree()
    51.     {
    52.         yield return new WaitForSeconds (7); //defending on the tree. because we want wait the tree fall first before cut it //again. if to slow, change it to 6 - 1. must same with treecontroller script, so it will best.
    53.         treeHasFalling = true;
    54.     }
    55. }
    56.  
    put these script on Main Camera (legacy character standard asset or unity 4 i think). or FirstPersonCharacter. now run the game. these script has been tested by me for a single tree in the scene. i will add it to my prefab later to make effect for all tree (using speedTree). and i'm not yet finished to make these tree spawn again. oh and be sure you have terrain, if not, after chopping it, the tree will falling down and down and deep and i dont know where it go xD. oops, i remember about yield wait for seconds . good luck my friends. hehehe

    EDIT : Speed Tree fail, when i use it, the collider work, but tree wont fall or health wont reduced. well that's all for now .
     
    Last edited: Feb 19, 2016
  14. FungusMonkey

    FungusMonkey

    Joined:
    Jun 30, 2016
    Posts:
    41
    For me the health is reduced and tree destroys but add force not working? Any answers?