Hello! I use this script to place the prefab:
#pragma strict
var spawnAreas : LayerMask; //Layers where you can spawn objects, make sure to fill this out
var destroyableObjects : LayerMask; //Objects that is ok to destroy, make sure to fill this out
var spawnPrefab : GameObject; //The object you want to spawn, in case you didn't assign the script creates a primitive
var grid : Vector3 = Vector3(1,1,1); //The grid you want to instantiate objects by
var colliderSize : Vector3 = Vector3(1,1,1); //The collider size of the object
var cam : Camera; //The camera you're using, in case you didn't assign one the script assigns the Main Camera
private var range : float = 100.0; //Don't use infinity, use the camera's far clipping plane if you need to
private var hit : RaycastHit;
function Start () {
cam = Camera.main;
}
function Update () {
if (Input.GetMouseButtonDown(0))
Build();
if (Input.GetMouseButtonDown(1))
Erase();
}
function Build () {
if (HitBlock(spawnAreas)) {
if (spawnPrefab==null) {
//In case you didn't have a prefab we spawn a primitive
spawnPrefab = GameObject.CreatePrimitive(PrimitiveType.Cube);
spawnPrefab.transform.position = Grid(hit.point);
} else {
//You have a prefab, let's spawn it
var spawnObject = Instantiate(spawnPrefab, Grid(hit.point), Quaternion.identity);
}
}
}
function Erase () {
if (HitBlock(destroyableObjects))
Destroy(hit.transform.gameObject);
}
function HitBlock (mask : LayerMask) : boolean {
var ray = cam.ScreenPointToRay (Input.mousePosition);
return Physics.Raycast(ray, hit, range, mask);
}
function Grid (pos : Vector3) : Vector3 {
return Vector3(Mathf.Round(pos.x/grid.x)*grid.x-(colliderSize.x/2), Mathf.Round(pos.y/grid.y)*grid.y+(colliderSize.y/2), Mathf.Round(pos.z/grid.z)*grid.z-(colliderSize.z/2));
}
But as you can see, I can only place a prefab.
You can change this code in such a way that:
Clicking a button changes the selected prefab in another?
example:
The initial prefab is called “earth”, I click the button and it will place the prefab will no longer land but “stone”?
Where should I insert the string?
– TrontonThe string? If you mean the name of the prefab, then you wouldn't use the name when using an Array. Instead you would access it by its index ( somewhere from 0 to Array.Length - 1). So if you only have two prefabs in the array, they will be stored at index 0 and 1 respectively. If you want to access them by name, consider storing them in a Dictionary.
– goibonI mean: Where do I put this?: public GameObject[] prefabs;
– TrontonSame place as you have your spawnPrefab right now.
– goibon