Hi. I have a set of cubes which have a BoxCollider and Rigidbody attached. I want to cast a ray in the cubes onStart() to see if it is hitting a GreyCube next to it and if it is to disable it being able to move. Am I doing this correctly?
Here is the code I have in Start ():
void Start()
{
thrust = 7f;
gravity = 11.5f;
direction = GameObject.Find("gGameController").GetComponent<CubeScript>().direction;
if (direction == "left")
{
if (Physics.Raycast(transform.position, new Vector3(transform.position.x - 2, transform.position.y, transform.position.z), out ray))
{
if (ray.collider.tag == "tGreyCube")
{
hasStopped = true;
Debug.Log("hit");
}
}
}
pos = transform.position;
}
If it’s not working now, then try logging ray.collider.gameObject.name and see what you get.
I’d bet you get the cube doing the raycast’s name there. You’re raycasting from the center of the cube, which is like shooting a gun from inside your stomach - you’re gonna hit yourself first. The best thing to do would probably be to put the grey cube on a specific layer, and raycast using a mask for that layer. That way you’ll only hit the one object you’re seeking, even if other objects (like yourself) are in between.
It should work in Start, my guess would be unity can’t find the GameObject soon enough or something. Try putting Debug.Log() Statements in each if statement, see where the problem is! Do this in the Start()