Im newish to unity and am trying to make a “space station” object where you click to where you would like the object to spawn and it is instantiated there with the position and rotation being rounded (like snapped to a grid) and the code i have come up with snaps but for only the first click any help would be appreciated.
The code I have is:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpawnOnMouseclick : MonoBehaviour {
Ray myRay; // initializing the ray
RaycastHit hit; // initializing the raycasthit
public GameObject objectToinstantiate;
public GameObject JustSpawned;
public GameObject me;
void Update()
{
myRay = Camera.main.ScreenPointToRay(Input.mousePosition); // telling my ray variable that the ray will go from the center of
// my main camera to my mouse (This will give me a direction)
if (Physics.Raycast(myRay, out hit))
{ // here I ask : if myRay hits something, store all the info you can find in the raycasthit varible.
// things like the position where the hit happend, the name of the object that got hit etc..etc..
if (Input.GetMouseButtonDown(0))
{// what to do if i press the left mouse button
JustSpawned = Instantiate(objectToinstantiate, hit.point, Quaternion.identity);// instatiate a prefab on the position where the ray hits the floor.
print(hit.point);// debugs the vector3 of the position where I clicked
//JustSpawned.transform.LookAt(me.transform.position);
JustSpawned.transform.SetPositionAndRotation(new Vector3(Mathf.RoundToInt(JustSpawned.transform.position.x), Mathf.RoundToInt(JustSpawned.transform.position.y), Mathf.RoundToInt(JustSpawned.transform.position.x)), new Quaternion(Mathf.CeilToInt(JustSpawned.transform.rotation.x), Mathf.CeilToInt(JustSpawned.transform.rotation.y), Mathf.CeilToInt(JustSpawned.transform.rotation.z), Mathf.CeilToInt(JustSpawned.transform.rotation.x)));
//JustSpawned.transform.Translate(transform.forward, Space.Self);
JustSpawned.transform.LookAt(me.transform.position);
JustSpawned.transform.SetPositionAndRotation(new Vector3(Mathf.RoundToInt(JustSpawned.transform.position.x), Mathf.RoundToInt(JustSpawned.transform.position.y), Mathf.RoundToInt(JustSpawned.transform.position.x)), new Quaternion(Mathf.RoundToInt(JustSpawned.transform.rotation.x), Mathf.RoundToInt(JustSpawned.transform.rotation.y), Mathf.RoundToInt(JustSpawned.transform.rotation.z), Mathf.RoundToInt(JustSpawned.transform.rotation.x)));
JustSpawned.transform.Translate(transform.forward, Space.Self);
}// end upMousebutton
}// end physics.raycast
}// end Update method
}
,