- Home /
Counting number of blocks in an area
Title sums it up. I have been working on random generation lately. I have made it so when water is generated, there is a chance that a "water checker" is spawned. What I want the water checker to do is count the amount of water in the area to see if it is suitable for fish to spawn. Now I know how to spawn fish and all, but how would I start at a script that finds blocks with the name/Tag "Water" in a certain Radius and count them? I'm not asking anyone to write me a script, I want to learn how to do this for other things I'm going to make for random generation. Maybe if there's a link, or steer me in the right direction. thanks.
if your water tiles have colliders you could use an overlap sphere. http://docs.unity3d.com/Documentation/ScriptReference/Physics.OverlapSphere.html
then check all the hitColliders for the tag and increment a counter when one is found.
p.s. not posting this as an answer because I'm not sure if your tiles have colliders :)
Answer by LiverX! · Nov 06, 2013 at 01:58 PM
Create new array:
C# - GameObject[] array = GameObject.FindGameObjectsWithTag("Water");
JS - var array : GameObject = GameObject.FindGameObjectsWithTag("Water");
And using Vector3.Distance(a,b) counting the objects which is distance from "mark" is not greater than some number.
So I have got It to count the water blocks in the game, and display the number for me to see, but I need help on the distance thing. Here is my script so far.
var array : Array;
var NumberOfWaterBlocks = 0;
function Update(){
array = GameObject.FindGameObjectsWithTag("Water"); print(array); NumberOfWaterBlocks = array.length;
}
Now how would I be able to incorporate Distance? Ive tried some things but I don't know how to $$anonymous$$us the number if it is out of range, etc.... I don't even know where to begin.
So you can get the list or relevant game objects (per your code above), now you just need to count all of those objects within a certain distance from your spawnPosition... to calculate the distance:
Vector3.Distance(spawnPosition, waterObject.transform.position);
If you were using C# I would include the code for doing the actual counting, but I don't know the JS collection methods.
Ok here it is in C#... hopefully this helps you understand what I mean:
GameObject.FindGameObjectsWithTag("Water").Count(waterObject => Vector3.Distance(spawnPosition, waterObject.transform.position) < spawnRadius);
You would need to include System.Linq. Spawn position is hopefully self explanatory, and spawnRadius is the max distance from spawnPoint to count the water object.
Your answer
Follow this Question
Related Questions
Alternative To "SetEditorCurve"? 1 Answer
input.getaxis not working 0 Answers
Health not counting down? 1 Answer