Greetings,
I am new to unity and also to scripting, i wanted to generate a flat infinite terrain, with the help of only blocks(like in minecraft)…
I placed a block at the center of the world and attached a script to it which generated four other blocks at four cardinal directions, but what is found is that when i run the game, my instantiated blocks keep overlapping each other which causes a lag, so i tried placing colliders around block to check whether a block is near it or not, but it does not seem to work…
this is the script is used for the block…
var spawn : boolean = false; //this will be a boolean var to check whether to spawn or not.
var spawner : GameObject; // this will be a gameobject which spawns the new blocks
var Dis : int; //distance between the player and the block
var Player : Transform; // our player(gameobject with tag "Player:)
function Start () {
}
function Update () {
Player = GameObject.FindGameObjectWithTag("Player").transform; // getting the player
if(spawn) // checking if block has to spawned
{
spawner.SendMessage("SpawnNow"); // messaging spawner to instantiate blocks
spawn = false; // setting spawn to false to ensure only one block will be spawned.
}
Dis = Vector3.Distance(transform.position, Player.position); // calculating the distance between player and block.
if(Dis>20)
{
Destroy(gameObject); // destroying if the distance is more than 20 blocks.(taking size of one block as 1).
}
}
function OnTriggerEnter(other : Collider)
{
if(other.tag == "Player") // checking if Collider is player or not.
{
spawn = true; // player has come near, let's spawn a block.
}
}
function OnTriggerExit(other : Collider)
{
if(other.tag == "Player")// player has gone
{
spawn = false; // let's do not spawn now.
}
}
here is the script i used for my spawner, currently only spawning in one direction…
var Block : GameObject; // our prefab of the block to be generated.
var canSpawn : boolean = true; // can we spawn a block?
var targetpos : Vector3;
function Start () {
}
function Update () {
targetpos = Vector3(transform.position.x,0,transform.position.z+1);
}
function SpawnNow() // will be executed when the "DeleteBlock" Script orders us.
{
canSpawn = true;
var allBlocks : GameObject[] = GameObject.FindGameObjectsWithTag("Block");
// an array of all the blocks present in the game, can be upto 80 in size.
yield WaitForSeconds(0.1); // to prevent force acting on the block by physics engine.
if(canSpawn)//check if we are capable to spawn?
{
var newBlock = Instantiate(Block, targetpos, Quaternion.identity);
canSpawn = false;
for(var current : GameObject in allBlocks)
{
if(current.transform.position == targetpos)
{
Destroy(newBlock);
}
}
}
}
is there any solution to this, by which i can generate a flat terrain without the blocks overlapping?
so when i go back from the block collider and reneter, the blocks overlap, cant seem to figure this out, i think my spawner script is not configured correctly…