How to check if a prefab is on the ground?

Hi ,
so in my game i have trees as prefabs (modified) , and because they are , i can’t place them normally with the “Place Trees” option in terrains.
Once i placed them all one by one and worked for the time , but now i have to add a lot … so i decided to make a script for that.

This is how it’s supposed to work : I place prefabs all around the scene above the terrain , and according the script each tree keeps “Falling down” (or in other words decreasing the position.Y value) until it hits/collides with the terrain itself.

I wrote the “Falling down” and it works , but i don’t know what to use or how to use it in order to actually know when it hits the ground.

I have tried OnTriggerEnter and OnCollisionEnter from both sides (from the tree prefab , and from the terrain itself) but couldn’t nail it.

public class TreeAutoPlace : MonoBehaviour {

    public bool onGround;

    void Update () {
        if(!onGround)
            transform.position = new Vector3(transform.position.x,Mathf.Lerp(transform.position.y, transform.position.y - 0.5f,1f), transform.position.z); // "Tree Falling" down method
    }

    private void OnCollisionEnter(Collision collision) // This is the wrong code area
    {
        if (collision.gameObject.tag == "Terrain")
            onGround = true; //When it's true , it means the tree hit the ground and it should stop now.
    }
}

If anyone knows what i should write , or had a similar situation, any help would be greatly appreciated!
Thanks.

You could try this: Unity - Scripting API: Terrain.SampleHeight
How did you modify them so you can’t paint them normally if you don’t mind my asking?
Will you be losing billboarding and/or just not care? Just curious.

1 Like

Thanks! I’ll give it a go and tell you if it worked.
I made a tree prefab to add to it some essential scripts for the game (like : Treehouse building). if i paint them normally i can’t change them into how i want them. plus there’s a cut tree system in my game , i don’t think i can cut the tree itself if it was painted.

Ya , that may be true.
I think it’s possible to mess more with the tree system that you can “easily”, but… I don’t know how in detail.
Anyhow, I hope the sample height thing works for ya.

Yes it worked!!! Thank you so much man :slight_smile: You’re awesome.

Awesome, glad it worked. :slight_smile:
You’re welcome. Enjoy your game :slight_smile: