Destroying Objects

This script is made to harvest grass, click on the gameobject and it will remove itself, but when i click on one of those grassprefabs, all others disappear too. I don’t know what the problem could be, will you help me? I would like to use the prefab mutliple times

My script for harvesting grass for now ;

using UnityEngine;
using UnityEngine.UI;
using System.Collections;

public class HarvestingGrass : MonoBehaviour
{

public Text Message;
public Animation Animation;
public ParticleSystem Particles;
public Image Image;

bool destroyedgameObject;
private Rigidbody rb;

void DestroyGameObject()
{
Destroy(gameObject);
}

void DestroyScriptInstance()
{
// Removes this script instance from the game object
Destroy(this);
}

void DestroyComponent()
{
// Removes the rigidbody from the game object

Destroy(GetComponent());
}

void DestroyObjectDelayed()
{
// Kills the game object in 5 seconds after loading the object
Destroy(gameObject, 5);
}

// When the user presses Ctrl, it will remove the
// BoxCollider component from the game object
void Update()
{
if (Input.GetButton(“Fire1”) && GetComponent())
{
Destroy(GetComponent());
Destroy(gameObject);
Destroy(this);
Destroy(GetComponent());

}

}
}

what gameobject is this script attached to? each grass gameobject?
In the Update you’re doing way to many Destroys, once you do the Destroy(gameObject); the grass has been removed and the others will not finish.
If it’s on the each grass gameobject then this script looks ok and should not be removing all of them.

That code is pretty hard to read without code tags.

That said, the problem lies here:

void Update()
{
if (Input.GetButton("Fire1") && GetComponent<BoxCollider>())
{
Destroy(GetComponent<BoxCollider>());
Destroy(gameObject);
Destroy(this);
Destroy(GetComponent<Rigidbody>());
}

There’s nothing in that code that specifies that you clicked on this instance of grass. If all your grass objects share this same code, then they will all be destroyed once the “Fire1” button is pressed.

You’ll need to add some logic to check that you actually clicked on an object, and destroy only the clicked object.

There are several topics on how to do this:

wait I see the issue, pete saw it first. thanks man.
You need to use a ray cast to check what game object you hit. then only delete that one gameobject

Thank you all for commenting and figuring it out! I’ll take a look to see if i can fix my problem with the help provided by you as soon as possible!

Thanks :slight_smile: