Raycast is acting strangely

I’m trying to instantiate an object on top of another one. To do this I decided to draw raycast from above the first object and instantiate next object on hit.point. however. for some reason it always instantiates the object on y 0.05. this means the raycast goes through collider and reaches this very specific point.

here’s some other helpful info
the object we cast a ray on is a child of an empty game object. this object has a cube collider, not set to trigger, no rigidbody. there is no other object located before or after the object raycast needs to hit. There’s nothing on 0.05y.

here’s the relevant bit of code

if (Physics.Raycast(RayPos, transform.TransformDirection(Vector3.down), out hit,
    Mathf.Infinity))
{
    int ChosenFlora = Random.Range(0, biome.Flora.Length);
    print(hit.point);
    Instantiate(biome.Flora[ChosenFlora], hit.point, Quaternion.identity);
    Debug.DrawRay(RayPos, transform.TransformDirection(Vector3.down) * 1000, Color.cyan);
    Debug.LogError("stop");
}

This piece of code is a part of a procedural world generation project. and it’s task is to spawn trees, bushes, and other plants on top of existing tiles. this code is executed for each tile after everything else has been generated

Small update
It specifically works with the objects I want this code to work on.
My theory is that raycast for some reason reads tile’s original size which is small. 0.1 to be exact. But doesn’t realise that it has been changed previously in the code. I printed the localscale.y of tile before drawing raycast and it is updated there. I’m confused

That was in fact what was happening. managed to fix the problem by creating coroutine and starting to raycast after the end of frame

oof, stray away from ever using coroutines, as they wind up making more problems than they solve.

If you want a simple function of make a cube on the side of a cube hit, enjoy this script: :slight_smile:

public class AddCube : MonoBehaviour
{
    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            Ray ray=Camera.main.ScreenPointToRay(Input.mousePosition);
            if (Physics.Raycast(ray,out RaycastHit hit,500f))
            {
                Vector3 sideVector = new Vector3(
                    hit.transform.localScale.x * hit.normal.x,
                    hit.transform.localScale.y * hit.normal.y,
                    hit.transform.localScale.z * hit.normal.z);
                Instantiate(hit.transform.gameObject,
                    hit.transform.position + sideVector, hit.transform.rotation);
            }
        }
    }
}