Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by DMCH · Nov 27, 2012 at 04:01 PM · c#instantiateinvalidcastexception

InvalidCastException C#

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;    
         }
     }
 }
 
Comment
Add comment · Show 7
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image markpdolby · Nov 27, 2012 at 04:19 PM 0
Share

I tested out the script you posted and I had no errors, could you post the exact error that unity gives you?

avatar image DMCH · Nov 27, 2012 at 04:21 PM 0
Share

Hello $$anonymous$$arkPDolby,

It's a run-time error. This error is: Invalid Cast Exception: Cannot cast from source to destination type.

This is where it happens: brickArray[i,j] = (GameObject) Instantiate(brick, new Vector3(tempBrickStartX, tempBrickStartY, 0), Quaternion.identity);

Thanks!

avatar image MarkFinn · Nov 27, 2012 at 04:52 PM 0
Share

I assume the variable brick is assigned to in the editor? Can you double-check that assignment. I could see some oddities if the variable was null in that line, though I'd not have expected a cast error.

You could also try writing the line as

brickArray[i,j] = Instantiate(brick, new Vector3(tempBrickStartX, tempBrickStartY, 0), Quaternion.identity)as GameObject;

But I doubt it'll make much difference.

avatar image MarkFinn · Nov 27, 2012 at 04:53 PM 0
Share

Also, are there any scripts on the brick prefab/GameObject?

avatar image Landern · Nov 27, 2012 at 04:55 PM 0
Share

If you used as, you wouldn't get a null reference, you would put null into the array since it will not raise a null exception with as. So yeah, it will make a difference in a potentially bad way.

Show more comments

1 Reply

· Add your reply
  • Sort: 
avatar image
0
Best Answer

Answer by Meltdown · Nov 27, 2012 at 05:09 PM

Try changing the line to...

 brickArray[i,j] = GameObject.Instantiate(brick, new Vector3(tempBrickStartX, tempBrickStartY, 0), Quaternion.identity) as GameObject;
Comment
Add comment · Show 3 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Landern · Nov 27, 2012 at 05:10 PM 0
Share

if the resulting call to Instantiate is null, then null is being shoved into the array, i don't think that is what is desired. no exception will be thrown, the developer could check for null and not insert it, but still that doesn't feel desirable, could be wrong though.

avatar image DMCH · Nov 27, 2012 at 05:32 PM 0
Share

Thanks for your help, but in this case, the problem was inexperience on my part!

avatar image Meltdown · Nov 27, 2012 at 05:40 PM 0
Share

Please mark as answered so we know your problem is resolved.

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

14 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Multiple Cars not working 1 Answer

InvalidCastException: Cannot cast from source type to destination type. 1 Answer

C# Extending Script causes InvalidCastException on Instantiate 1 Answer

InvalidCastException when using Instantiate 1 Answer

Distribute terrain in zones 3 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges