Search Unity

How can I make a block placement system for a space survival game. (Minecraft-like)

Discussion in 'Scripting' started by JohnyTheCarrot, May 28, 2017.

  1. JohnyTheCarrot

    JohnyTheCarrot

    Joined:
    May 28, 2017
    Posts:
    1
    I'm very new to Unity and I'm for practice making a small survival game.
    I have found block-placement code on these forums somewhere, but this is VERY buggy.

    This is what I currently have:

    Code (CSharp):
    1. Ray ray = camera.ViewportPointToRay(new Vector3(0.5F, 0.5F, 0));
    2.         BoxCollider box = hit.collider as BoxCollider;
    3.  
    4.         if (Physics.Raycast(ray, out hit))
    5.         {
    6.             print("I'm looking at " + hit.transform.name);
    7.             box.GetComponent<Renderer>().material = Looking;
    8.  
    9.             if (Input.GetMouseButtonDown(1))
    10.             {
    11.                 Destroy(box.gameObject);
    12.                 print("Removed block");
    13.             }
    14.  
    15.             if (Input.GetMouseButtonDown(0))
    16.             {
    17.                 Vector3 V = new Vector3(Mathf.Ceil(hit.point.x), Mathf.Ceil(hit.point.y), Mathf.Ceil(hit.point.z));
    18.                 Instantiate(prefab, V, box.transform.rotation, parent.transform);
    19.                 print("Block Added");
    20.             }
    21.  
    22.             else
    23.                 print("I'm looking at nothing!");


    Sometimes it even places the block inside the other ones.

    Could someone please fix this code for me?
    Thanks in advance.
     
    Last edited: May 28, 2017