Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 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 /
  • Help Room /
avatar image
0
Question by Lunatic_Method · Nov 22, 2015 at 05:50 PM · c#methodsinvalidcastexceptionwhats-wrong

Unity returns InvalidCastException when attempting to run a method from another file

Okay, so. Everything was going smoothly until I ran into this one peculiar problem, that the internet does not seem to have an answer for. This is my main script that calls stuff from other scripts.

 using UnityEngine;
 using baseFunct;
 using mobFunct;
 using mapFunct;
 
 [RequireComponent(typeof(AudioSource))]
 public class gm : MonoBehaviour
 {
     public float hor;
     public float ver;
 
     public void Start()
     {
         Vector3 startpos = new Vector3(1, 1, 0);
         World testworld = mapf.genWorld("testworld", 4);
         mapf.renderCell(testworld.cell[new Vector3(0, 0, 0)]);
         mapf.derenderCell(testworld.cell[new Vector3(0, 0, 0)]);
         Mob player = new Mob();
         player = mobf.spawnMob("Player", startpos);
     }
 
     void Update()
     {
         hor = Input.GetAxisRaw("Horizontal");
         ver = Input.GetAxisRaw("Vertical");
         if (Input.anyKey)
         {
             //Do a thing
         }
     }
 }

At the line

 player = mobf.spawnMob("Player", startpos);

It seems to die. I get an "InvalidCastException: Cannot cast from source type to destination type."

This is the file that contains the method:

 using UnityEngine;
 using mapFunct;
 
 namespace mobFunct
 {
     public class Mob  //define our base mob
     {
         public string name = "unnamed";
         public Vector3 worldpos = new Vector3(0,0,0);
         public GameObject model = new GameObject();
 
         public bool moveTo(World t_world, Vector3 t_pos)
         {
             if (t_world.block[t_pos].is_open) {
                 worldpos = t_pos;
                 model.transform.position = t_pos;
                 return true;
             } else { return false; }
         }
     }
 
 
 
     public class mobf : MonoBehaviour
     {
         static public Sprite[] m_sprite = (Sprite[])Resources.LoadAll("gfx/mob");
         static public GameObject genericmob = (GameObject)Resources.Load("genericmob");
 
         static public Mob spawnMob(string newname, Vector3 newpos)
         {
             Debug.Log(newname);
             Debug.Log(newpos);
             Mob newmob = new Mob();
             newmob.name = newname;
             newmob.model = (GameObject)Instantiate(genericmob,newpos,Quaternion.identity);
             newmob.model.GetComponent<SpriteRenderer>().sprite = m_sprite[1];
             return newmob;
         }
     }
 
 
 }

As far as I can tell, there is literally no reason I should be getting this error. It happens during run-time, Visual Studio doesn't find anything.

I am not casting. I have examined another file where I attempt to call a similar method. Everything is done the exact same way. I have tried commenting out the contents of the method and making it a public static void. Totally empty. And it returns the same exception. I then tried copypasting it (still empty) to mapf, which contains my mapFunct namespace. It worked fine.

Comment
Add comment
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

2 Replies

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

Answer by Lunatic_Method · Nov 22, 2015 at 08:06 PM

Ah, thank you so much for your speedy and insightful response, Statement. Thanks to your suggestion (and a nap) I was able to find a way around the problem.

I decided to use a list to handle the loading of sprites. Will probably work better that way anyways.

The problem was connected to those two lines, as you suggested. I moved the genericmob declaration inside my spawnMob method, and incorporated the filling out of a list into a method of it's own while also adding a type to Resources.Load, as shown here. It worked like a charm.

     public class mobf : MonoBehaviour
     {
         static public List<Sprite> m_sprites = new List<Sprite>();
 
         static public void loadSprites()
         {
             m_sprites.Add((Sprite)Resources.Load("gfx/mob/prot_hero",typeof(Sprite)));
         }
 
         static public Mob spawnMob(string newname, Vector3 newpos)
         {
             GameObject genericmob = (GameObject)Resources.Load("genericmob");
             Debug.Log(newname);
             Debug.Log(newpos);
             Mob newmob = new Mob();
             newmob.name = newname;
             newmob.model = (GameObject)Instantiate(genericmob,newpos,Quaternion.identity);
             newmob.model.GetComponent<SpriteRenderer>().sprite = m_sprites[0];
             return newmob;
         }
     }
Comment
Add comment · 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
1

Answer by Statement · Nov 22, 2015 at 06:11 PM

Are you sure the exception doesn't happen somewhere inside mobf.spawnMob? Looks odd to me. Also looks odd that you create a mob that you then toss away Mob player = new Mob(); in gm.Start but that shouldn't matter. What I can see could possibly go wrong is:

 static public Sprite[] m_sprite = (Sprite[])Resources.LoadAll("gfx/mob");
 static public GameObject genericmob = (GameObject)Resources.Load("genericmob");

These initializers will be called when the class is initialized. Please initialize the static variables in a method so you more easily can debug if either of these casts fail. I would guess that your Sprite[] cast will fail if gfx/mob contain anything else than Sprites for example.

If the call to mobf.spawnMob is the first time you access mobf, then it would make sense that either of those could fail.

Comment
Add comment · 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

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

35 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 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 avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Declared variable being returned as null in a method? 0 Answers

How can i pass a method like a parameter Unity3d C#? 3 Answers

C# Ambiguity problem with default overloads 0 Answers

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

How do I call a method with variables in it? 1 Answer


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