Checking for a gameobject at a position
I am trying to make a spawner button for my 2D-TBS game, i have gotten the object to spawn, but i am still trying to make a check to see if there is a game object at that location, other wise i get objects overlapping and pushing each other out of the way, i am drawing a complete blank on how to do it code wise, but i do know i need colliders, so i have place Boxcollider2Ds on everything thats gonna collide with something on the same layer
my code is included below, my objective here is to check if there is a gameobject at a current position, and if there is an object at that position, to spawn the object at a different position instead,
using UnityEngine; using System.Collections; using UnityEngine.UI; using Random = UnityEngine.Random;
public class Mspawn : MonoBehaviour { public Button button; public BoardManager boardManger; public int x; public int y; public Vector3 CheckPosition; void OnEnable(){ if (Input.GetMouseButtonDown(0)) { button.onClick.AddListener (SpawnUnit); }
}
void awake(){
boardManger = GetComponent<BoardManager> ();
}
void SpawnUnit()
{
/*Debug.Log ("Testing...");
for (int i = 0; i < boardManger.PlayerUnits.Length; i++)
{
//this code is dysfunctional, im still working on it. just ignore it
Debug.Log (boardManger.PlayerUnits.Length);
if (boardManger.PlayerUnits[i] == GameObject.FindWithTag("PlayerSoldierMarksman"))
{
Debug.Log("Testing complete");
Instantiate (boardManger.PlayerUnits[i], new Vector3 (1, 1,0f), Quaternion.identity);
}
}*/
Instantiate (boardManger.PlayerUnits[3], new Vector3 (randomSpawnPosition), Quaternion.identity);
}
public void checkPosition(Vector3 check)
{
check = randomSpawnPosition ();
//this is obviously the location for what i'm trying to do;
}
Vector3 randomSpawnPosition()
{
int x = Random.Range(0,2);
int y = Random.Range(0,2);
Vector3 Position = new Vector3 (x, y);
return Position;
}
}
Answer by Jordi-Bonastre · May 12, 2016 at 03:48 PM
I think that you can use Physics.Linecast from top to bottom, assigning the correct layer and check if there is any collision with a player or whatever are you instantiating. Maybe there are options more elegant, but this is what I should do in 5 minutes. http://docs.unity3d.com/ScriptReference/Physics.Linecast.html
this seems a little overkill for checking a single square beside me for a collision
Your answer
Follow this Question
Related Questions
Collision inside a local function 2 Answers
Objects not colliding 1 Answer
Reach other object animator when collide and play animation 1 Answer
How can i put down a sprite on collision? 0 Answers
How do I change level/scene? 1 Answer