Hello to all,
I want to make the following tutorial
(you have to place cubes in a grid)
I can make the grid, but I can not create cubes by clicking on the white image (sort of white plane below the grid).
Here is my code of the tutorial, there is probably an error (but the debugger show no errors )
- PLaceObjectOnGrid
public class PlaceObjectOnGrid : MonoBehaviour
{
public Transform gridCellPrefab;
public Transform cube;
public Transform onMousePrefabe;
public Vector3 smoothMousePosition;
[SerializeField] private int height;
[SerializeField] int width;
private Vector3 mousePosition;
private Node[,] nodes;
private Plane plane;
void Start()
{
CreateGrid();
plane = new Plane(Vector3.up, transform.position);
}
void Update()
{
GetMousePositionOnGrid();
}
void GetMousePositionOnGrid()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (plane.Raycast(ray, out var enter))
{
mousePosition = ray.GetPoint(enter);
print(mousePosition);
smoothMousePosition = mousePosition;
mousePosition.y = 0;
mousePosition = Vector3Int.RoundToInt(mousePosition);
foreach (var node in nodes)
{
if (node.cellPosition == mousePosition && node.isPlaceable)
{
if (Input.GetMouseButtonUp(0) && onMousePrefabe != null)
{
node.isPlaceable = false;
onMousePrefabe.GetComponent<ObjFollowMouse>().isOnGrid = true;
onMousePrefabe.position = node.cellPosition + new Vector3(0, 0.5f, 0);
onMousePrefabe = null;
}
}
}
}
}
public void OnMouseClickOnUI()
{
// if (onMousePrefabe == null)
{
onMousePrefabe = Instantiate(cube, mousePosition, Quaternion.identity);
}
}
private void CreateGrid()
{
nodes = new Node[width, height];
var name = 0;
for (int i = 0; i < width; i++)
{
for (int j = 0; j < height; j++)
{
Vector3 worldPosition = new Vector3(i, 0, j);
Transform obj = Instantiate(gridCellPrefab, worldPosition, Quaternion.identity);
obj.name = "Cell " + name;
nodes[i, j] = new Node(true, worldPosition, obj);
name++;
}
}
}
public class Node
{
public bool isPlaceable;
public Vector3 cellPosition;
public Transform obj;
public Node(bool isPlaceable, Vector3 cellPosition, Transform obj)
{
this.isPlaceable = isPlaceable;
this.cellPosition = cellPosition;
this.obj = obj;
}
}
}
- And 2 ObjFollowMouse
public class ObjFollowMouse : MonoBehaviour
{
private PlaceObjectOnGrid placeObjectOnGrid;
public bool isOnGrid;
void Start()
{
placeObjectOnGrid = FindObjectOfType<PlaceObjectOnGrid>();
}
// Update is called once per frame
void Update()
{
if (! isOnGrid)
{
transform.position = placeObjectOnGrid.smoothMousePosition + new Vector3(0, 0.5f, 0);
}
}
}
Indeed, I can only place one cube in the grid, then I click and nothing happens.
Your help is welcome,
A+