Hello friends,
I’m working on a breakout clone, and have run into some difficulty with an invalid cast exception. I’m using an Array of GameObjects to store the bricks, so it will be easy to iterate through them and set their strengths, points, colours etc.
The code compiles ok, and the error occurs at runtime. This error is: Invalid Cast Exception: Cannot cast from source to destination type. This error occurs near the bottom of the script, I’ve marked it out with a comment block.
Can someone point out where the problem is?
Also, if you could, I’d really like an explanation as to whether in scripts, prefabs should be declare as type Transform, or GameObject? I’ve seen it done as both, but don’t understand the rationale. Thanks!
using UnityEngine;
using System.Collections;
public class GameControl : MonoBehaviour
{
/** INSTANCE FIELDS **/
public GameObject brick;
public GameObject [,] brickArray;
// Layout Fields
private float brickStartX;
private float brickStartY;
// Use this for initialization
void Start ()
{
// Instantiate Variables
brickStartX = -9.5f;
brickStartY = 5;
brickArray = new GameObject [5, 12];
// Instantiate Bricks
CreateBricks();
}
// Update is called once per frame
void Update ()
{
}
// Instantiates Bricks at the start of a level
void CreateBricks()
{
float tempBrickStartX = brickStartX;
float tempBrickStartY = brickStartY;
for(int i = 0 ; i < 5 ; i++)
{
for(int j = 0 ; j < 12 ; j++)
{
/*
*
* Error occurs here
*
*/
brickArray[i,j] = (GameObject) Instantiate(brick, new Vector3(tempBrickStartX, tempBrickStartY, 0), Quaternion.identity);
tempBrickStartX += 1.71f;
}
tempBrickStartX -= 20.52f;
tempBrickStartY -= 0.50f;
}
}
}