Raycast hit : runtime vs variable

In my game, I have a function called every frame like the following

public static void Vehicle_Idle_DownHit(GameGod gameGod, CarControl vehicleAI)
    {
        RaycastHit hit;
        Vector3 startPos = new Vector3(vehicleAI.Mytransform.position.x + 1, vehicleAI.Mytransform.position.y + 1, vehicleAI.Mytransform.position.z);
        //Debug.DrawRay(startPos, vehicleAI.Mytransform.TransformDirection(Vector3.down), Color.red);

        switch (Physics.Raycast(startPos, vehicleAI.Mytransform.TransformDirection(Vector3.down), out hit, 2, gameGod.Layers[0]))
        {
            case true:
                vehicleAI.Mytransform.rotation = Quaternion.LookRotation(Vector3.Cross(vehicleAI.Mytransform.TransformDirection(Vector3.right), hit.normal));
                vehicleAI.Mytransform.position = new Vector3(vehicleAI.Mytransform.position.x, hit.point.y, vehicleAI.Mytransform.position.z);

        }
    }

Having seen that the raycastHit struct is quite complex (it has a collider, an rb, etc.) Having to call it on 10 different objects at the same time, to optimize performances it is better for me to create a raycastHit variable for each of these objects, and use that as a reference , or can I create it at runtime (like in the example)?

Your example is perfectly valid and causes no performance penalties related to RaycastHit.

RaycastHit is a struct, so it’s allocated in the stack in the same way as a Vector3 or a float. Allocating local variables in the stack is always O(1) no matter the size or complexity of the variable. Note that the collider, rigidbody, etc inside RaycastHit are just references (pointers) to the objects that are residing in the heap (a different area of the memory).

1 Like