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

Spawn GameObject when Ray Collides

Discussion in 'Scripting' started by TheLeon, Nov 22, 2014.

  1. TheLeon

    TheLeon

    Joined:
    Nov 22, 2014
    Posts:
    3
    I want to create a Script, which spawns the GameObject "MainObject" at the position, where my Ray hits the GameObject with the Tag "Wall". How can I do this?
    At the moment I have this script:

    Code (csharp):
    1.  
    2.     public string tag = "Wall";
    3.     public GameObject MainObject;
    4.     void Update()
    5.     {
    6.         if (Input.touchCount == 1)
    7.         {
    8.             Touch touched = Input.GetTouch(0);
    9.             RaycastHit hitted;
    10.             Ray ray = Camera.main.ScreenPointToRay(touched.position);
    11.  
    12.             if (Physics.Raycast(ray, out hitted, distance))
    13.             {
    14.                 if (hitted.collider.CompareTag(tag))
    15.                 {
    16.                     Vector3 create = new Vector3(touched.position.x,touched.position.y,0);
    17.  
    18.                     Instantiate(MainObject, create, Quaternion.identity);
    19.                 }
    20.             }
    21.  
    22.         }
    23.  
    24.  
    25.  
    26.     }
    27.  
     
  2. Suddoha

    Suddoha

    Joined:
    Nov 9, 2013
    Posts:
    2,824
    The RaycastHit class provides useful information.
    In your case, if hitted is not null, you can get the position with
    Code (CSharp):
    1. hitted.point
     
  3. TheLeon

    TheLeon

    Joined:
    Nov 22, 2014
    Posts:
    3
    Do you mean: Vector 3(hitted.point.x, hitted.point.y, hitted.point.z); ?
     
  4. Stardog

    Stardog

    Joined:
    Jun 28, 2010
    Posts:
    1,886
    Yes, or just put:
    Code (CSharp):
    1. Instantiate(MainObject, hitted.point, Quaternion.identity);
     
  5. TheLeon

    TheLeon

    Joined:
    Nov 22, 2014
    Posts:
    3
    Ok, thx!