Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

How do I spawn an object where my crosshair is pointing?

Discussion in 'Scripting' started by Fantom7655, Dec 23, 2020.

  1. Fantom7655

    Fantom7655

    Joined:
    Oct 13, 2018
    Posts:
    9
    So I'm working on a prototype of a game and I have a very limited knowledge of C#, I was wondering how to spawn or create an object at the position my raycast hits. I have a simple raycast script and fire sequence but I don't know how to spawn the object. Can you Help Me? Thanks In advance!!!!!!!


    Here's My Raycast Code.

    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. public class PlaceRocketEngine : MonoBehaviour
    4. {
    5.    //I was going to assign the model that I wasnted to spawn here.
    6.     public GameObject thrusterModel;
    7.  
    8.     void Update()
    9.     {
    10.         RaycastHit hit;
    11.  
    12.        
    13.  
    14.         if (Input.GetButtonDown("Fire1"))
    15.         {
    16.             print("You Shot A Raycast!!!!");
    17.             if (Physics.Raycast(transform.position, -Vector3.up, out hit))
    18.             {
    19.                 print("Found an object - distance: " + hit.distance);
    20.             }    
    21.         }
    22.  
    23.     }
    24. }
     
  2. AbandonedCrypt

    AbandonedCrypt

    Joined:
    Apr 13, 2019
    Posts:
    69
    The coordinate where your raycast-hit is stored is hit.point.

    You can use Object.Instantiate() to create a new gameobject at a certain coordinate in world space.
     
  3. Fantom7655

    Fantom7655

    Joined:
    Oct 13, 2018
    Posts:
    9
    So it would be
    Code (CSharp):
    1. Object.Instantiate(transform.hit.point)
    Or did I do something wrong?
     
  4. Fantom7655

    Fantom7655

    Joined:
    Oct 13, 2018
    Posts:
    9
    Never mind I got It working! Thanks for your help!