Raycasting to place turrets

Hi, I am trying to make a tower defence game for university project and have decided to place turrets by clicking on the game object in the inventory and then selecting a square to place it on. I have already placed the turret game object on the square but have it inactive. I was thinking that if i used a raycast to select the visible game object in the inventory i could make a bool for it = true once the ray cast hit it. then i would select the square i want the turret to be place on and write turret.active=true. I’m not entirely sure how to code this though, this is what I have so far

public class MainCameraScript : MonoBehaviour {

public bool turret = false

void Start () {
}

void Update () {
if(Input.GetMouseButtonDown(0))
{
Ray ray=Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit= new RaycastHit();
if (Physics.Raycast(ray,out hit))
{
if(hit.collider.gameObject.name==“TurretChoice”)
{
turret= true;
}

}
}

Hi, welcome to the forum!

What you have so far looks OK. Is the problem now to determine where to put the turret? You can get the position that the ray hit an object using the point field from the RaycastHit object. You will need to have a plane or other object with a collider to act as the “ground” against which the ray will hit. You can then use the Instantiate function to create a new turret at the desired position.

Thanks for replying andeeee, i managed to get it working now. here it is

public class MainCameraScript : MonoBehaviour
{

public bool turret = false;
public GameObject turret1;
public GameObject turret2;
public GameObject turret3;
public GameObject turret4;
public GameObject turret5;
public GameObject turret6;
public GameObject turret7;

// Use this for initialization
void Start()
{
}

// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit = new RaycastHit();
if (Physics.Raycast(ray, out hit))
{
if (hit.collider.gameObject.name == “TurretChoice”)
{
turret = true;
}
if (Input.GetMouseButtonUp(0))
{
turret = false;
}
}
}
if (turret == true)
{

if (Input.GetMouseButtonUp(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit = new RaycastHit();
if (Physics.Raycast(ray, out hit))
{
if (hit.collider.gameObject.name == “TurretBase1”)
{
turret1.active = true;
}
if (hit.collider.gameObject.name == “TurretBase2”)
{
turret2.active = true;
}
if (hit.collider.gameObject.name == “TurretBase3”)
{
turret3.active = true;
}
if (hit.collider.gameObject.name == “TurretBase4”)
{
turret4.active = true;
}
if (hit.collider.gameObject.name == “TurretBase5”)
{
turret5.active = true;
}
if (hit.collider.gameObject.name == “TurretBase6”)
{
turret6.active = true;
}
if (hit.collider.gameObject.name == “TurretBase7”)
{
turret7.active = true;
}
}
}
}
}
}