- Home /
Check for collision in for loop c#
Hello, I am trying to check for a collision while a for loop is running. But what ever i try it seems the for loop runs all the way through before it checks for any collisions. I want the xaxis and yaxis to debug.Log when collision occurs while its still in the loop.
public class GrassTile1 : MonoBehaviour {
public GameObject BoxChecker;
public static int xaxis=0;
public static int yaxis=0;
void OnCollisionEnter(Collision col)
{
Debug.Log(xaxis);
Debug.Log(yaxis);
}
void Start()
{
//spawn box checker
for (int p = 1; p < 11; p++)
{
for (int i = 1; i < 11; i++)
{
GameObject cubeSpawn = (GameObject)Instantiate(BoxChecker, new Vector3(i - 0.5f, p - 0.5f, -0.4f), transform.rotation);
xaxis++;
OnCollisionEnter();//i was thinking i could call the collision method like this but that doesnt work
}
yaxis++;
}
}
}
many many many thanks for answers
Answer by robertbu · Sep 25, 2014 at 06:18 PM
It cannot be done this way. OnCollisionEnter() is a callback made by Unity to your code. It must be a function declared in your code that gets called. It is not a function you call. See the reference for examples. And nothing here check for a collision.
I'm not sure what you are trying to do here, so it is hard to advise. Often Physics.CheckSphere() is used to detect if a position is open for placement.