- Home /
Spawn object on ground
i made a animal spawn script but my animals are spawning at y 500 so that they dont spawn under the map. how could i make it that my animals spawn on the ground and not 500 on the y axis or under tha map. my map has alot of mountains
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AnimalSpawner : MonoBehaviour
{
public Transform animalSpawner;
public GameObject Animal;
public int xPos;
public int zPos;
public int animalCount = 10;
private LightningManager lightManager;
void Start()
{
lightManager = GameObject.FindObjectOfType<LightningManager>();
}
void Update()
{
if (animalCount <= 50){
SpawnAnimasl();
}
}
void SpawnAnimasl()
{
while (animalCount < 10)
{
xPos = Random.Range(1, 1600);
zPos = Random.Range(1, 1600);
Instantiate(Animal, new Vector3(xPos, 500, zPos), Quaternion.identity);
animalCount += 1;
}
}
}
The way I would go about it is to find your spawn point at y:500 and raycast down to the map mesh, take note of the distance and take that way from your y:500 and you have your ground spawn point.
Answer by AbandonedCrypt · Feb 09, 2021 at 09:08 AM
Physics.Raycast up from your calculated random xz-position at y = 0 (or wherever your lowest terrain point is) until you hit a ground collider, then instantiate your animal at the hit.point
. That should handle both cases of them spawning too far up and below terrain.
(Pseudo)-Code:
if(Physics.Raycast(rndPos, Vector3.up, out RaycastHit hit))
Instantiate(prefab, hit.point, Quaternion.identity);
Make sure to check if you hit ground! E.g. by comparing tags, or (ideally) using a layermask.
did you spelled Identity wrong or something, becouse it tells me: 'Quaternion' does not contain a definition for 'Identity'
identity works but what should i assign as rndPos, a transform or something else? sorry for my bad englisch by the way
Answer by Khar03 · Feb 09, 2021 at 07:30 AM
You can use raycast to get distance from animal to ground and then move that animal down by that distance.
This does not handle animals spawning below terrain in the case that 500 is lower than e.g. a mountain.
Your answer
![](https://koobas.hobune.stream/wayback/20220613024823im_/https://answers.unity.com/themes/thub/images/avi.jpg)