How to change the direction of spawning of an object just before colliding a wall like object??

Hello I am creating a scene in which cubes need to be created only at the edges of the room like a cube will be there on clicking it new cube should be attached to previous one and continue so on and if there will be a collision spawning next it should change its direction like rotate 90degrees and spawn again.
Any help??

Please someone answer!!!1

Your wording is a bit vague so it’s hard to understand what behavior you’re actually looking for. You can change the object’s rotation when you instantiate it:

Instantiate(myObject, position, rotation) as GameObject;

If you want to rotate it based on the rotation of some other object you’ll first have to get that object’s rotation… something like this:

 void OnCollisionEnter(Collision col)
{
    Vector3 rotDeg = col.transform.eulerAngles + new Vector3(0, 0, 90);
    AnotherBox = Instantiate(myObject, transform.position, Quaternion.Euler(rotDeg)) as GameObject;
}