How to check altitude of an object C#
Hey, at the beginning I have to say that I'm a newbie in Unity, so forgive me if this problem is too basic :P
I have generated objects in my game that player should collect, their position is random. I want to define that when there is an object on one altitude, there won't be second one on the same.
The objects are generated with Instantiate in a for loop, so there is no way to save them in many variables, they are just too many. They have a transform parent in common.
GameObject clone = (GameObject) Instantiate (clone, position, Quaternion.identity);
It creates many objects with the same name, but at least I can operate with the created object until loop ends
Thanks in advance, ask if I haven't explained something clearly enough / forgot to say something :)
Answer by jdean300 · Aug 14, 2016 at 10:14 AM
List<float> spawnedHeights = new List<float>();
//your for loop logic
for (...){
//Somehow you're generating a random position
Vector3 positon = ...;
while (spawnedHeights.Contains(position.y)){
positon = /*get new random position here*/;
}
//spawn as you normally would
GameObject clone = ...;
}
This will only keep them from spawning at exactly the same height. If instead you want them to be certain distance from eachother in altitude:
List<float> spawnedHeights = new List<float>();
//your for loop logic
for (...){
Vector3 positon = Vector3.zero;
bool posFound = false;
while (!posFound){
positon = /*get random position here*/;
posFound = true;
for (int i = 0; i < spawnedHeights.Count; i++){
//replace the 10f with whatever gap you want
if (Mathf.Abs(position.y - spawnedHeights[i]) < 10f){
posFound = false;
break;
}
}
}
//spawn as you normally would
GameObject clone = ...;
}
Big thanks, after a few combinations and changes it worked perfectly :D
Thank you once again!
Your answer

Follow this Question
Related Questions
Is It possible to Instantiate Objects in parallel? 0 Answers
How would I make a destructible object script? 0 Answers
How can I find object ? 2 Answers
Array.Sort() - JS only???! 0 Answers
How do i "Lock" a platform in place? 1 Answer