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

Question Trying to instantiate objects on top of a mesh, but nothing happens

Discussion in 'Prefabs' started by Hydropug, Aug 24, 2020.

  1. Hydropug

    Hydropug

    Joined:
    Apr 20, 2020
    Posts:
    1
    Hello, I am trying to spawn objects on top of a mesh I made using raycasting to locate the mesh, and then instantiate said objects on top of the mesh, but whenever I start my application in the editor, It says that it cannot put that object there. I put in a few lines of code that would say that whenever the script cannot find anything to place the object on.

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using System.Security.Cryptography.X509Certificates;
    4. using UnityEngine;
    5.  
    6. public class RockGenSmall : MonoBehaviour
    7. {
    8.     public int rocks = 30;
    9.     public int rocknum = 0;
    10.     public GameObject rock1;
    11.     public GameObject rock2;
    12.     public GameObject rock3;
    13.     public int rockchoice = 0;
    14.     public float maxDistance;
    15.  
    16.     void Start()
    17.     {
    18.         for(int i = 0;i < rocks; i++)
    19.         {
    20.             RaycastHit hit;
    21.             rockchoice = Random.Range(1, 3);
    22.             if (Physics.Raycast(new Vector3(Random.Range(-100f, 100f), 10f, Random.Range(-100f, 100f)), Vector3.down, out hit, maxDistance))
    23.             {
    24.                 if(rockchoice == 1)
    25.                 {
    26.                     Instantiate(rock1, hit.point, Quaternion.identity);
    27.                     rocknum++;
    28.                 }
    29.                 if (rockchoice == 2)
    30.                 {
    31.                     Instantiate(rock2, hit.point, Quaternion.identity);
    32.                     rocknum++;
    33.                 }
    34.                 if (rockchoice == 3)
    35.                 {
    36.                     Instantiate(rock3, hit.point, Quaternion.identity);
    37.                     rocknum++;
    38.                 }
    39.             }
    40.             else
    41.             {
    42.                 Debug.Log("cannot place that there!");
    43.             }
    44.         }
    45.     }
    46. }
    47.