Hello,
I have looked at several threads on how to remove a tree from a terrain (during the game), and I’ve written my own script. But I can’t figure out why my script won’t work. I should say that most of the examples are in C# (of course
), and I mainly use Javascript/Unityscript. But that aside, I still am at a loss as to why it’s not working.
Here is my script:
//#pragma strict
public var amountOfWood : int = 100;
//Tree array for the terrain data
private var treeArray : TreeInstance[];
private var treeArrayJS = new Array();
private var distance : float;
private var terrain : TerrainData;
private var i : int;
private var thisTransform : Transform;
//The closest tree's position
private var closestTreePosition : float;
//Nearest tree to the collider
private var nearestTree : TreeInstance;
function Start () {
thisTransform = transform;
treeArray = Terrain.activeTerrain.terrainData.treeInstances;
treeArrayJS = new Array(treeArray);
//Debug.Log(treeArrayJS.length);
terrain = Terrain.activeTerrain.terrainData;
}
function Update () {
if(amountOfWood <= 0) {
// Our current closest tree initializes to far away
var maxDistance : float = Mathf.Infinity;
for (i = 0; i < treeArrayJS.length; i++)
{
//Get the trees world position on the terrain
var treePosition : Vector3 = Vector3.Scale(treeArrayJS[i].position, terrain.size);
//Check the distance between the tree collider and the tree's position
closestTreePosition = (treePosition - thisTransform.position).sqrMagnitude;
if(closestTreePosition < maxDistance) {
maxDistance = closestTreePosition;
nearestTree = treeArrayJS[i];
//Debug.Log(nearestTree);
}
}
// Remove the tree from the terrain tree list
treeArrayJS.Remove(nearestTree);
treeArray = treeArrayJS.ToBuiltin(TreeInstance) as TreeInstance[];
}
}
When this script executes, nothing happens. I don’t get any errors, but nothing at all happens.
Thanks for any help.