Instantiating an object with the correct rotation

I would like to instantiate an object with the correct rotation but unsure about how I’d do it. If i Instantiate the object on a flat surface it looks fine but if I Instantiate on a vertical or sloped wall, it looks weird. Take the below image as an example:


The slime on the right is flat on the ground but the one on the left is in the same rotation but sticking from the wall. Is there a way I can get the object to like against the wall for a more natural look? This is the code I’m currently using:

I found a post [here][2] that says I should rotate according to the normals of the object which makes sense but I am still having no luck using the following code:

    RaycastHit hit;
    Vector3 dir = -transform.up;
    float length = 0.35f;

    Debug.DrawRay(transform.position, dir * length,;

    if (Physics.Raycast(transform.position, dir * length, out hit, length))
        SpawnObject(null, manager.slimeBalls, transform.position, Quaternion.LookRotation(hit.normal));

Just for reference, this is the SpawnObject code I am using:

void SpawnObject(Collider col, List<GameObject> objectList, Vector3 position, Quaternion rotation)
        //For each artifact in the list
        for (int i = 0; i < objectList.Count; i++)
            //If a artifact is inactive
            if (!objectList*.activeInHierarchy)*

//Set the position to the collision point
objectList*.transform.position = position;*

//Set the rotation to the rotation collision point
objectList*.transform.rotation = rotation;*

//Set the artifact to active

//break from the loop

At the moment, you’re telling your object’s “forward” direction to orient itself facing outward from the surface it’s sitting on.

To get the rotation you’re trying for, you need to add a small, extra step to your process.

Using FromToRotation(), you can adapt your rotation into a small tweak rather than a large change in direction.

Quaternion newDirection = Quaternion.FromToRotation(transform.up, hit.normal);

SpawnObject(null, manager.slimeBalls, transform.position, newDirection);

On this basis, the newDirection would be attained as a relative rotation to the spawner. As an alternative, “Vector3.up” could be used as an alternative to “transform.up” in case the spawner would be rotated.