Object spawn issues

Hello,

I have an inventory system and you can also drop items. Whenever I drop an item I Instantiate the pickup prefab in front of the player:

Vector3 spawnPosition = playerObj.gameObject.transform.position;
spawnPosition = spawnPosition + playerObj.gameObject.transform.forward * 2;
 
ItemPickUpScript dropObject = (ItemPickUpScript)Instantiate(Item.dropPrefab, spawnPos, Quaternion.identity) as ItemPickUpScript;

But the problem I have is that if you’re too close to an object (e.g. a wall) you spawn the prefab inside the other object (e.g. a wall). I tried checking if something is infront of the player by doing a raycast and if it is I check the distance and then if the distance is less than something I put a spawnPos as raycast hit point.

But by doing that I Instantiate the object half into the wall. And also whenever I check the distance I also ignore the fact that various pick up objects might be in a different sizes as well, so maybe the prewritten distance value might not be too accurate.

Is there a good way in fixing this issue? Thanks!

The raycasting idea sounds good, but as you said, it also needs to account for the size of the object. You could get that size by checking the bounds of its renderer: Renderer.bounds.