Search code examples
c#unity-game-engineterrainprefab

How can I generate terrain rather than an object on drag and drop in Unity?


Background

I would like to know how to write a code that a player can generate terrain by drag and drop in Unity3D version 2020.3.

What I tried so far

I can create terrain before execution for unchangeable background and land during the executing time.

And the case of objects(prefabs), I confirmed that a player could generate a new object at selected positions.

code which was attached to a gameobject

ClickSphere.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class ClickSphere : MonoBehaviour
{
    public GameObject prefab;
    private Vector3 mousePosition;
 
    void Update()
    {
        if (Input.GetMouseButtonDown(0)) //the case of drag -> OnMouseDrag() 
        {
        mousePosition = Input.mousePosition;
        mousePosition.z = 10.0f;
        Instantiate(prefab, Camera.main.ScreenToWorldPoint(mousePosition),Quaternion.identity);
        }
    }
}

How can I attach a code to terrain and how can I approach for terrain compared to object generation?


Solution

  • If you are trying to do this in a 3D project, i suggest you place a plane(on which you can place the objects). And than cast a ray from the camera(in the cameras orientation http://docs.unity3d.com/ScriptReference/Physics.Raycast.html) and depending on the object that the ray hits, intantiate the object you want to place at the height at which the ray hit. So you can generate the terain you want and than, when the user needs to place stuff, it wont overlap because you know the point of intersection between the ray and whatever terain you initialy generated.