How To Move Object To Terrain Slope in C# With Raycast?

I am trying to get a object to the same x and z as the terrain below it. My method right now is to get Raycast to get the normal and then trying to mess with transform.eulerAngles
until they are the same. I fear this might be a little over my head though as I cannot figure this out for the life of me and I have been trying for several hours.

using UnityEngine;
using System.Collections;

public class example : MonoBehaviour {
	public Vector3 hitr;
	public Vector3 hitrn;
	
	
    void Update() {
        RaycastHit hit;
		Physics.Raycast(transform.position, Vector3.down, out hit);
		if (Physics.Raycast(transform.position, Vector3.down, 2)){
			hitr = hit.normal;
			hitrn = hitr - transform.eulerAngles;
			transform.Rotate(hitrn.x, 0, hitrn.z);
		}
    }
}

I see that you have two choices:

  • Presuming the normal coming from the raycast hit is what you need (it looks right when you use it):

    transform.up = hit.normal;

  • If that doesn’t do it, it might be better to sample a couple of points around the base of your model and then work out the slope angle from that

Look in the docs at this component of the hit…

http://unity3d.com/support/documentation/ScriptReference/RaycastHit-barycentricCoordinate.html

That script there draws a Debug Line in the editor window, but you can modify it to do what you want.