- Home /
Spawn single floor tile at mouse position
Hello, I am trying to build an RCT, Prisonarchitect or Sim like game in Unity2D.
The idea is that I press a UI button, get a tile that follows the mouse and by pressing the mouse button a clone of that tile spawns at the mouse(x;y) location.
This should not be a problem since this is pretty much basic.
But When I try to place a single tile I get a ton of tiles in the same place. Somehow I need way to scan for an already existing tile (or other game_object) that is already placed at that location.
I have tried it with "Tags" but I could not get to work. My script so far is also for unity3D I have tried to modify it so that it don't need the Vector3 component but it did not work either.
I have no idea. I am desperate right now. The solution can't be that difficult but I am not able to see it.
-Thanks
var depth = 10.0;
var FloorPrefab : Transform;
function Update ()
{
//Follow mouse
var mousePos = Input.mousePosition;
var wantedPos = Camera.main.ScreenToWorldPoint (Vector3 (mousePos.x, mousePos.y, depth));
transform.position = wantedPos;
{
//Spawn object at mouse position
var mousex = Input.mousePosition.x;
var mousey = Input.mousePosition.y;
var ray = camera.main.ScreenPointToRay (Vector3(mousex,mousey,0));
var hit : RaycastHit;
}
if ( Input.GetMouseButtonDown(1) )
{
Destroy(gameObject);
}
if (Physics.Raycast (ray, hit, 200))
{
if ( Input.GetMouseButtonUp(0) )
{
var create = Instantiate(FloorPrefab, hit.point, Quaternion.identity);
}
}
}
Hmm, not really sure but do you have the script attached to the floortile that you are spawning? I'm asking because i think maybe when you instantiate one floortile in the script that script on the instantiated floortile spawns a new one and so on...
Yes the script is attached to the floortile. But this should not be the problem. If I understand this correct then I have to make sure that the script only spawns a new tile if there is no other game_object in the way. But how ??
You can check the desired position for and already existing object with a Raycast. Read this: http://docs.unity3d.com/ScriptReference/RaycastHit-collider.html
You can use the .collider info that you get to deter$$anonymous$$ if there is a object with (for example) the tag "floortile".
Also in line 25 the mouse button up? looks like it should be a mouse button down, it looks like this input is checking to see if the button is not pressed, then placing object.
Answer by Mentaner · Aug 05, 2014 at 10:49 PM
Thank you!
I have done it with tags on colliders
Works like a Dream!
function Update ()
}
if (Physics.Raycast (ray, hit) && hit.collider.gameObject.CompareTag("Ground"))
{
if ( Input.GetMouseButtonDown(0) )
{
var create = Instantiate(FloorPrefab, hit.point, Quaternion.identity);
}
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613155813im_/https://answers.unity.com/themes/thub/images/avi.jpg)