I have a Minecraft like script for placing and destroying blocks. When I try to destroy a block the whole game crashes and I dont know why. I also dont know how to change the cube to a block prefab I have called Grass Block.
Script -
var blockLayer : LayerMask = 1;
var range : float = Mathf.Infinity;
var hit : RaycastHit;
function Update () {
if (Input.GetMouseButtonDown(0))
Build();
if (Input.GetMouseButtonDown(1))
Erase();
}
function Build() {
if (HitBlock()) {
var cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
cube.transform.position = hit.transform.position + hit.normal;
}
}
function Erase() {
if (HitBlock())
Destroy(hit.transform.gameObject);
}
function HitBlock() : boolean {
return Physics.Raycast(transform.position, transform.forward, hit, range, blockLayer);
}
So we got a few wierd things here. First off this physics cast to the blockLayer. You create a layer, you cast only to a layer, but there is nothing in that layer.
At what point did you assign the cubes you generate to the blockLayer?
I’d not worry about layers right now, just try to make it work without to start.
whats this attached to?
Is there anything at all in the blocklayer?
do this insert a log to figure out what your trying to destroy. Perhaps its the player.
function Erase(){
if (hitblock())
{
Debug.log(hit.transform.gameObject);
}
as to how to create a prefab this is in c# but its easy to transfer
this is my create object script
public class CreateObject : MonoBehaviour {
public GameObject temp;
// Update is called once per frame
void Update () {
if (Input.GetKeyDown(KeyCode.Alpha1))
{
temp.rigidbody.isKinematic = true;
temp.transform.position = Camera.main.ViewportToWorldPoint(new Vector3(.5f, .5f, 3));
Instantiate(temp);
}
}
}
notice i have a public gameobject called temp.
that shows up in the inspector as something i can see when i have the script selected.
I then drag my prefab over it and now temp is whatever prefab i dragged onto it.
i then modify the position of the object each time to make sure it will be created in the right spot and then use the keyword Instantiate to bring it into the game.