Hard time converting small piece of js code to csharp...

I got extracted this code from a way bigger script I found elsewhere I can’t find again a few days ago. I tried converting it to csharp without succes. Its mainly the two last lines that I can not convert.

Basically it is a script that orient an object so it aligns with floor or slope orientation.

function Update (){
       var hit: RaycastHit;

       Physics.Raycast(transform.position, -Vector3.up, hit);
       var hitRotation = Quaternion.FromToRotation(Vector3.up, hit.normal);
       transform.rotation.x = hitRotation.x;
}

I have tried many things and got many different error messages.

Here is that code in C#:

public class SomeClass : Monobehavior
{
    RaycastHit raycastHit;

    void Update()
    {
        Physics.Raycast(transform.position, -Vector3.up, out raycastHit);
        Quaternion hitRotation = Quaternion.FromToRotation(Vector3.up, hit.normal);
        transform.rotation = new Quaternion(hitRotation.x, transform.rotation.y, transform.rotation.z, transform.rotation.w);
    }
}

The quaternion stuff is a bit tricky…not sure whether it will work as a verbatim translation from Javascript. You can’t change a single property of a transform struct like that - you need to create a whole new struct, kind of cumbersome.

rotation is a property from transform, and you can’t change their components directly. You have to pass an entire Quaternion. Eg:

var currentRot = transform.rotation;
currentRot.x = hitRotation.x; //It's OK to change components of a local variable
transform.rotation = currentRot;

A keyword out must precede the variable hit to tell C# that this variable will be used to return some value, and in the last line you must use an auxiliary variable, because C# doesn’t accept modification of a single component of a property (rotation is a property of Transform):

void Update (){
    RaycastHit hit;

    Physics.Raycast(transform.position, -Vector3.up, out hit);
    Quaternion hitRotation = Quaternion.FromToRotation(Vector3.up, hit.normal);
    // the last line makes no sense, but it could be translated to:
    Quaternion rot = transform.rotation; // copy rotation to an aux variable...
    rot.x = hitRotation.x; // change the x component in that variable...
    transform.rotation = rot; // then assign it to rotation
}

NOTE: The last line isn’t right: rotation is a quaternion, and represents a single rotation about some axis; the components x, y and z are this axis in a coded format, and modifying the x component alone may produce very weird results.