I have a collectable that I am trying to spawn on terrain. I have 2 Vector3s which are the bounds of the spawning (they make the collectable always within the terrain), and then when I pick a random x and z coordinate within those boundaries (with a y coordinate that is above all terrain). Then, I shoot a raycast directly down and set the collectable’s y coordinate to y of the point that was hit.
However, it seems like the raycast never hits anything because the Debug.Log isn’t printing out into the console. I don’t know why it doesn’t hit though, since the collectables always spawn within the terrain (the terrain has a terrain collider, it doesn’t have a physics material if that is important)
using UnityEngine;
public class CollectableSpawner : MonoBehaviour
{
public int spawnedCollectables;
[SerializeField] private Vector3 corner;
[SerializeField] private Vector3 oppositeCorner;
[SerializeField] private LayerMask prohibitedSpawnAreaLayer;
[SerializeField] private GameObject collectable;
private int collectables;
private void Awake() => collectables = Random.Range(PlayerCollectableManager.MinCollectables, PlayerCollectableManager.MaxCollectables + 1);
private void Start()
{
while (spawnedCollectables != collectables)
{
Vector3 _spawnPosition = new Vector3(Random.Range(corner.x, oppositeCorner.x), 100, Random.Range(corner.z, oppositeCorner.z));
Transform _collectableTransform = Instantiate(collectable).GetComponent<Transform>();
_collectableTransform.position = _spawnPosition;
if (Physics.OverlapBox(_collectableTransform.position, _collectableTransform.localScale / 2,
Quaternion.identity, prohibitedSpawnAreaLayer).Length > 0)
{
Destroy(_collectableTransform.gameObject);
continue;
}
//following code should bring collectable down
Ray _downRay = new Ray(_collectableTransform.position, new Vector3(_collectableTransform.position.x,
Mathf.NegativeInfinity, _collectableTransform.position.z));
//placing spawnedCollectables += 1; inside the if makes an infinite loop
if (Physics.Raycast(_downRay, out RaycastHit _hitInfo))
{
Debug.Log($"Raycast point y: {_hitInfo.point.y}");
_collectableTransform.position = new Vector3(_collectableTransform.position.x, _hitInfo.point.y, _collectableTransform.position.z);
_collectableTransform.rotation = Random.rotation;
}
spawnedCollectables += 1;
}
}
}