I am using a great little script that will destroy terrain trees within an explosion and instantiate a dead replacement:
public class TreeExplosion : MonoBehaviour {
public float BlastRange = 10.0f;
public float BlastForce = 2000.0f;
public GameObject DeadReplace;
public GameObject Explosion;
void Explode() {
Instantiate(Explosion, transform.position, Quaternion.identity);
TerrainData terrain = Terrain.activeTerrain.terrainData;
ArrayList instances = new ArrayList();
foreach (TreeInstance tree in terrain.treeInstances) {
float distance = Vector3.Distance(Vector3.Scale(tree.position, terrain.size) + Terrain.activeTerrain.transform.position, transform.position);
if (distance<BlastRange) {
// the tree is in range - destroy it
GameObject dead = Instantiate(DeadReplace, Vector3.Scale(tree.position, terrain.size) + Terrain.activeTerrain.transform.position, Quaternion.identity) as GameObject;
dead.GetComponent<Rigidbody>().maxAngularVelocity = 1;
dead.GetComponent<Rigidbody>().AddExplosionForce(BlastForce, transform.position, BlastRange*5, 0.0f);
} else {
// tree is out of range - keep it
instances.Add(tree);
}
}
//Delete original tree
terrain.treeInstances = (TreeInstance[])instances.ToArray(typeof(TreeInstance));
}
void Update() {
if (Input.GetButtonDown("Fire1")) {
Explode();
}
}
}
There are two issues with this script which I cannot work out.
1) Is it possible to only hide/disable a terrain tree temporarily? This is because otherwise, if Player A “goes on a rampage” and destroys all trees in the game level; when Player B comes along to play the same level, there won’t be any trees left for them to destroy! It would be better to be able to hide/disable any trees within the explosion, and then on Awake simply unhide/enable all terrain trees. This way any player will be able to “go on a rampage”.
2) Using the TerrainData class, it is possible to access individual tree instances of a terrain. However is it also possible to access grass in this way? The reason is that I would like to be able to destroy both the trees and grass (at the moment it is only trees), but I am not quite sure how terrain grass is accessed via script. Can it be done using the TerrainData class, or in some other way?