Tree Cutting Script broken

Well ive followed some guy on YT with his Tree cut script but now ive ran into the problem that when i cut 1 tree all the others in the “Group” (i have to create an Empty Gameobject and group the Tree Prefab with it in order to work) will be cutt down. I think its because of the setting: thisTree = transform.parent.gameObject;
But i have no idea how to tell the script that i want to cut down only the tree infront of my raycast. Anyone got an idea?
This is the Tree Script itself:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Tree : MonoBehaviour
{
    GameObject thisTree;
    public int treeHealth = 5;
    private bool isFallen = false;

    private void Start()
    {
        thisTree = transform.parent.gameObject;
    }

    private void Update()
    {
        if(treeHealth <= 0 && isFallen == false)
        {
            Rigidbody rb = thisTree.AddComponent<Rigidbody>();
            rb.isKinematic = false;
            rb.useGravity = true;
            rb.AddForce(Vector3.forward, ForceMode.Impulse);
            rb.mass = 6;
            rb.drag = 4;
            StartCoroutine(destroyTree());
            isFallen = true;
        }
    }

    private IEnumerator destroyTree()
    {
        yield return new WaitForSeconds(5);
        Destroy(thisTree);
    }
}

And this is the Axe Script(Raycast):

using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.Design;
using System.Security.Cryptography;
using UnityEngine;

public class AxeRaycast : MonoBehaviour
{
    public GameObject axe;
    private bool isEquiped = false;

    private void Update()
    {
        if(!axe.activeSelf && Input.GetKeyDown(KeyCode.Alpha1))
        {
            isEquiped = true;
            axe.SetActive(true);
        }
        else if(Input.GetKeyDown(KeyCode.Alpha1))
        {
            isEquiped = false;
            axe.SetActive(false);
        }

        Vector3 fwd = transform.TransformDirection(Vector3.forward);
        RaycastHit hit;

        if(Physics.Raycast(transform.position,fwd, out hit, 10))
        {
            if(hit.collider.tag == "tree" && Input.GetMouseButtonDown(0) && isEquiped == true)
            {
                Tree treeScript = hit.collider.gameObject.GetComponent<Tree>();
                treeScript.treeHealth--;
            }
        }
    }
}

If your tree script is on each tree then you can just get rid of the thisTree variable and replace it with gameObject.

1 Like

Yeah, well, why would you do that? You tell your script that ‘thisTree’ is the parenting gameobject. Afterwards, if health on this script was reduced to zero, you add a rigidbody component to thisTree, meaning the parent object, and make it fall. What do you need the ‘thisTree’ variable for? It should work if you just remove it completely.

1 Like

allright thanks guys got it now :slight_smile: