Making instantiated object stick to terrain at mouse position.

Updated on May 19, 2017 in [A] Unity Scripting
Share on Facebook0Tweet about this on TwitterShare on Google+0Share on Reddit0
2 on May 18, 2017

Hello everyone!
Im making a city builder game, and im trying to get a gameobject to stick to the terrain at the mouse position, before it is placed.
When i press the button that is supposed to instantiate the building at mouse pos unity crashes.
Im new to unity so i might be doing something really stupid please bear with me :D.

using UnityEngine;
public class BuildingsManager : MonoBehaviour {
 GameObject building;
 public GameObject buildRef;
 Ray ray;
 RaycastHit hitinfo;
 public void Construct(string buildingName)
 {
 foreach (Transform child in buildRef.GetComponentInChildren<Transform>())
 {
 if (buildingName == child.name)
 {
 building = child.gameObject;
 GameObject newBuilding = Instantiate(building, transform.position, Quaternion.identity);
 while (!Input.GetMouseButtonDown(1))
 {
 ray = Camera.main.ScreenPointToRay(Input.mousePosition);
 if (Physics.Raycast(ray, out hitinfo))
 {
 newBuilding.transform.position = hitinfo.transform.position;
 if (Input.GetMouseButtonDown(0))
 {
 return;
 }
 }
 }
 Destroy(newBuilding);
 return;
 }
 }
 }
}
 

  • Liked by
Reply
1 on May 18, 2017

i figured it im an idiot lol.

Devoted
on May 19, 2017

I just love these types of moments, you bash your head for hours and then you just immediately say, I’m an idiot!

Show more replies
  • Liked by
Reply
Cancel