Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

How to place instantiated prefab on ground?

Discussion in 'Prefabs' started by coder_58, Jul 8, 2021.

  1. coder_58

    coder_58

    Joined:
    Mar 29, 2020
    Posts:
    31
    Hi,
    I have this code which basically creates a tree in front of the player when the user clicks:

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. public class SpawnTrees : MonoBehaviour
    5. {
    6.     public GameObject tree;
    7.      public float distance;
    8.      void Start(){
    9.      }
    10.      //Vector3 playerPos = transform.position;
    11.      //Vector3 playerDirection = transform.forward;
    12.      float spawnDistance = 10;
    13.      // Update is called once per frame
    14.      void Update()
    15.      {
    16.          if (Input.GetMouseButtonDown(0)){
    17.              Vector3 playerPos = transform.position;
    18.              Vector3 playerDirection = transform.forward;
    19.              Vector3 spawnPos = playerPos + playerDirection*spawnDistance;
    20.              Debug.Log(spawnPos);
    21.              Instantiate(tree, spawnPos, Quaternion.identity);
    22.          }
    23.      }
    24.      
    25. }
    This works fine. But the issue is that the trees are being created a little above the ground instead of directly on top of the ground. Can someone please help me fix this? thanks!
     
    Bakanovskiy95 likes this.
  2. DerDicke

    DerDicke

    Joined:
    Jun 30, 2015
    Posts:
    291
    Maybe adding an offset value to spawnPos?
    Like:

    public float yOffset;


    And add it like:

    spawnPos+= Vector3.up*yOffset;
     
    Bakanovskiy95 likes this.