- Home /
trying to create a script to cut down trees but once i cut down the first tree it starts bugging
MissingReferenceException: The object of type 'GameObject' has been destroyed but you are still trying to access it. Your script should either check if it is null or you should not destroy the object. UnityEngine.GameObject.GetComponent[ChopScript] () (at C:/buildslave/unity/build/artifacts/generated/common/runtime/GameObjectBindings.gen.cs:38) PlayerScript.OnTriggerStay (UnityEngine.Collider other) (at Assets/PlayerScript.cs:20)
Thats what it says when i cut down the first tree wondering if there is a way to do it with tags or just another way.
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class PlayerScript : MonoBehaviour { public GameObject tree; public bool axe; public float moveSpeed; public Canvas CanvasObject;
void OnTriggerStay(Collider other)
{
if (axe == true)
{
if (Input.GetMouseButtonDown(0))
{
tree.GetComponent<ChopScript>().strength = tree.GetComponent<ChopScript>().strength - 1;
}
}
}
void Start () {
axe = false;
CanvasObject.enabled = false;
moveSpeed = 1f;
}
void Update () {
if (Input.GetKeyDown("1"))
{
axe = true;
CanvasObject.enabled = true;
}
if (Input.GetKeyDown("2"))
{
axe = false;
CanvasObject.enabled = false;
}
transform.Translate(moveSpeed*Input.GetAxis("Horizontal")*Time.deltaTime, 0f, moveSpeed*Input.GetAxis("Vertical") * Time.deltaTime);
}
}
Second script
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class ChopScript : MonoBehaviour { public int strength;
void Start () {
strength = 5;
}
void Update () {
if (strength == -0)
{
Destroy(gameObject);
}
}
}
Answer by MT369MT · Jun 07, 2018 at 08:19 PM
Hi, your mistake is the variable public GameObject tree; You probably assigned it in the inspector but you can’t do it because you don’t know which tree you will cut down. You should instead get the tree components by collision like:
void OnTriggerStay(Collider other)
{
if (other.gameObject.tag == “tree” && axe == true)
{
if (Input.GetMouseButtonDown(0))
{
other.gameObject.GetComponent<ChopScript>().strength -= 1:
}
}
Create a tree tag and assign it to your tree prefab. I also modified your strenght decrement because i think doing -= 1 is faster. In your second script why wrote you if (strenght == -0)? It is better if you write if (streght
Your answer
![](https://koobas.hobune.stream/wayback/20220612164332im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How can I change some tree's radius and length in C# script? 1 Answer
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Tree render distance. 1 Answer
Illuminating a 3D object's edges OnMouseOver (script in c#)? 1 Answer