- Home /
The question is answered, the right answer was accepted.
Object-Spawning Script?
I am creating a game which requires trees that can be cut down.
The trees are the objects that I want spawned in the world, but it is far too much effort and cluttering-up of the hierarchy window to drag and drop each one over six full-size terrains, therefore I need a script to spawn these trees for me.
I also require the spawning script to spawn the trees with a custom script applied to them, one each, so that I may apply to the trees a chopping script that I have ready. I also require them to have colliders.
I will gratefully use C# and Boo scripts, but I would much prefer it if the scripts could be written in Java-Script, because I can fix errors and understand that language.
Thank you in advance for anybody with good intentions, from one who gives the solution, to one who wanted to help but didn't have the knowledge.
Answer by JusticeAShearing · Jul 22, 2014 at 03:34 PM
I ended up using this script. I spent a month trying to find this out, and eventually arrived back to where I started. With some amendments, this script is now error-free and my own. #pragma strict
//This script finds all the terrain's trees then creates the tree object for user interaction for each tree position
//The tree is a transform
var treeFab : Transform;
//The selected terrain is a certain terrain
var grabTerrain : Terrain;
//The trees are in an instance
var trees : TreeInstance[];
function Start ()
{
//For when i is worth zero, i gets the tree instances data on the active terrain and its length
for (var i=0; i <Terrain.activeTerrain.terrainData.treeInstances.Length; i++)
{
//The terrain is that which is active
var terrain : TerrainData = Terrain.activeTerrain.terrainData;
//The positions at which we are to make trees are that of the tree instances
var pos = Vector3.Scale(Terrain.activeTerrain.terrainData.treeInstances[i].position,terrain.size)+ Terrain.activeTerrain.transform.position;
//Create the trees
Instantiate(treeFab, pos, Quaternion.identity);
}
}
I hope that others find that they need not go on a learning-circle, and arrive right back to where they started after a month of learning their coding language.
This script is written in Java Script.
Does anyone have the time to convert this to C#? Thank you.
You should take the time to learn how to do it yourself. There's really not a lot of difference.
You can do this by comparing the examples in the Scripting Reference.