From zero to a complete Unity3D game: 3D Concentration using C# – step 3: multiple instances of the same object and camera movement

In this third step of the 3D concentration game we’ll see how to create multiple instances of an object, how to move the camera and how to add a background plane.

If you have missed them, check from zero to a complete Unity3D game: 3D Concentration using C# – step 1 for the bare bones and step 2: skinning and timing to know how to join game objects and handling timers.

Basically, at this point we have a tile which can be flipped but now we want an arbitrary number of tiles placed in rows and columns, moreover we want to place the camera in order to see all tiles no matter of their number, and a plane where to lie tiles.

It may seem a lot of things but actually it’s very easy, although I had to modify Mainscript.cs a bit:

While I only added one line to CubeScript.cs

And this is the result:

Click on tiles to flip them.

Now, we are ready to use real graphics, which will be explained next week.

Download the source code of the entire project.

  • Y8

    Thanks for the article. Looks very difficult..

  • Leandro

    Nice tutorial. You could only explain some of the calcs made in Mainscript.cs.
    Also, in this class, the code:
    cube.transform.localScale=new Vector3 (2,2,0.5f);
    should be:
    cube.transform.localScale=new Vector3 (tileSize,tileSize,0.5f); // right? and the same for the quad.
    About the “next week” tutorial, I haven’t found it.

  • Leandro

    There was a mistake regarding tileSize and tileSpacing. They were not being used in camera position calculation.
    The correct is:
    for (int i = 0; i < rows; i++) {
    for (int j = 0; j < cols; j++) {
    // a cube
    GameObject cubo = GameObject.CreatePrimitive (PrimitiveType.Cube);
    cubo.transform.localScale = new Vector3 (tileSize, tileSize, 0.5f);
    cubo.renderer.material.color = new Color (255, 0, 0);
    cubo.transform.localPosition = new Vector3((tileSize+tileSpacing)*j, (tileSize+tileSpacing)*i, 0);
    cubo.AddComponent ("CubeScript");
    // a quad
    GameObject face = GameObject.CreatePrimitive (PrimitiveType.Quad);
    face.transform.localScale = new Vector2 (tileSize, tileSize);
    face.transform.Rotate (0, 180, 0);
    face.transform.position = new Vector3 ((tileSize+tileSpacing)*j, (tileSize+tileSpacing)*i, 0.251f);
    face.renderer.material.color = Color.blue;
    // attaching the quad to the cube
    face.transform.parent = cubo.transform;
    }
    }

    // the camera, we want to point on the middle of the board
    float cameraX = ((cols-1)*tileSize+(cols-1)*tileSpacing)/2f;
    float cameraY = ((rows-1)*tileSize+(rows-1)*tileSpacing)/2f;
    // setting camera height, this should work with every number of tiles
    float cameraZ = Mathf.Max (cols,rows)*-(tileSize+tileSpacing);
    Camera.main.transform.localPosition = new Vector3(cameraX, cameraY, cameraZ);