Search Unity

Characters don´t instantiate, need some help.

Discussion in 'Scripting' started by chicoPerdido, Oct 23, 2018.

  1. chicoPerdido

    chicoPerdido

    Joined:
    Oct 23, 2018
    Posts:
    1
    I'm making an rts game and I want to instantiate a selected unity (based on the toggle that is On), in the spawnPosition. Basically it doesn't work. You have the code below.

    Code (CSharp):
    1. void Update()
    2.     {
    3.         if (toggle1.isOn)
    4.         {
    5.             RaycastHit hitInfo;
    6.             Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    7.  
    8.             if (!EventSystem.current.IsPointerOverGameObject())
    9.             {
    10.                 if (Physics.Raycast(ray, out hitInfo))
    11.                 {
    12.                     if (hitInfo.collider.tag == "CubePrefab")
    13.                     {
    14.                         if (Input.GetMouseButton(2))
    15.                         {
    16.                             Vector3 spawnLocation = new Vector3(Input.mousePosition.x, 1.5f, Input.mousePosition.y);
    17.                             Instantiate(unit1, spawnLocation, Quaternion.identity);
    18.                         }
    19.                     }
    20.                 }
    21.             }
    22.         }
    23.         else if (toggle2.isOn)
    24.         {
    25.             RaycastHit hitInfo;
    26.             Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    27.  
    28.             if (!EventSystem.current.IsPointerOverGameObject())
    29.             {
    30.                 if (Physics.Raycast(ray, out hitInfo))
    31.                 {
    32.                     if (hitInfo.collider.tag == "CubePrefab")
    33.                     {
    34.                         if (Input.GetMouseButton(2))
    35.                         {
    36.                             Vector3 spawnLocation = new Vector3(Input.mousePosition.x, 1.5f, Input.mousePosition.y);
    37.                             Instantiate(unit2, spawnLocation, Quaternion.identity);
    38.                         }
    39.                     }
    40.                 }
    41.             }
    42.         }
    43.     }
    I have a two public game objects, and two public toggles created also.
     
  2. Vryken

    Vryken

    Joined:
    Jan 23, 2018
    Posts:
    2,106
    You most likely need to convert your mouse position from screen space to world space.
    This can be accomplished by using Camera.ScreenToWorldPoint and supplying
    Input.mousePosition
    as the parameter.