Search Unity

Need help for snapping to Grid

Discussion in 'Editor & General Support' started by PE2, Mar 24, 2018.

  1. PE2

    PE2

    Joined:
    Sep 9, 2017
    Posts:
    32
    Hey Guys, I am making an RTS game and I am trying to snap my Ghost prefab building during run-time after I instantiate it using the UI button, and I want to use the Mathf Round function. However, for past month, I have tried many functions to get it to work, including the Mathf Floor, but the Ghost prefab does not snap to grid for some reason, so I removed the function. Here is my script, if anyone can help that would be nice. Thank you.

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.UI;
    5. using System.Linq;
    6.  
    7. public class ObjectPlacement : MonoBehaviour {
    8.    
    9.     public GameObject BuildingPrefab; //Actual building. This will be placed from another script called 'BuildingSafe'.
    10.     public GameObject GhostBuildingPrefab; //Ghost prefab which will be instantiated after clicking the UI button.
    11.     private Transform currentBuilding;
    12.     public float  RotateSelf = 3f; // for Rotating the building during runtime before placement.
    13.     private Transform transform;
    14.     private BuildingSafe safeBuilding;
    15.  
    16.     // Use this for initialization
    17.     void Start () {
    18.     }
    19.    
    20.     // Update is called once per frame
    21.     void Update () {
    22.  
    23.         Ray ray = Camera.main.ScreenPointToRay (new Vector3(Input.mousePosition.x, Input.mousePosition.y, Input.mousePosition.z));
    24.         RaycastHit hit = new RaycastHit();
    25.         if (Physics.Raycast (ray, out hit, Mathf.Infinity)) {
    26.             hit.point = new Vector3(hit.point.x, hit.point.y, hit.point.z);
    27.             currentBuilding.transform.position = hit.point;
    28.         }
    29.  
    30.         if (Input.GetKeyDown(KeyCode.R)){
    31.  
    32.             currentBuilding.transform.Rotate(Vector3.back, RotateSelf, Space.Self);
    33.         }
    34.  
    35.         if (Input.GetKeyDown(KeyCode.Q)){
    36.  
    37.             currentBuilding.transform.Rotate(Vector3.forward, RotateSelf, Space.Self);
    38.         }
    39.  
    40.  
    41.     }
    42.  
    43.     //For instantiating a Ghost prefab after clicking the UI button.
    44.     public void CreateBuilding() {
    45.         currentBuilding = GameObject.Instantiate(GhostBuildingPrefab).transform;
    46.         safeBuilding = currentBuilding.GetComponent<BuildingSafe> (); //The Ghost prefab will check whether the building is safe to place or not before clicking.
    47.         safeBuilding.BuildingPrefab = BuildingPrefab;
    48.     }
    49. }