- Home /
Cast object to monobehaviour
I am trying to cast an object[] to monobehaviours, and even though I've copied the same logic used in the Resources.LoadAll documentation it still wont work. If I run the script this way, it says cannot cast source type to destination type. If I remove the "(MonoBehaviour)" cast it says "a cast exists, did you forget to use one?" or something like that.
Object[] scripts = Resources.LoadAll ("BossScripts");
pool = new MonoBehaviour[scripts.Length];
for(int x=0;x<pool.Length;x++)
{
pool[x] = (MonoBehaviour) scripts[x];
}
What are you trying to do with the BossScripts? You normally don't do a Resources.Load for a script and it's most likely not the right approach for what you're trying to accomplish.
I'm dynamically loading and adding scripts because I don't want contributors to have to edit the prefab/scene in order to add something.
do you load ANY items if you use this version of LoadAll() (from the docs):
$$anonymous$$onoBehavior[] pool=Resources.LoadAll<$$anonymous$$onoBehavior>("BossScripts");
It sounds like gameObject.AddComponent()
should fit your needs. That's the standard approach.
@Glurth "The type or namespace "$$anonymous$$onoBehaviour" could not be found"
edit: No it "works" it was just a typo. However, it doesn't find anything. Is there another type that would detect C# scripts
Answer by MaxMallon · Sep 19, 2017 at 07:44 AM
I have a game controller that spawns the player, and adds a component to it based on choices made in the menu. The 'standard approach' of having it be linked to added components doesn't make any sense here. The game controller doesn't need any of the scripts the player gets added, and I can't just put them all on the player too, as they're all child-scripts of a parent type, and would do conflicting stuff. I made an array of scripts which could be added, and at first used MonoScript, but then it turned out that doesn't work in a build.. (makes me wonder why it's even there to begin with =__=) Now I'm trying with Objects, but it just won't cast it back into the right data-type to be able to add it onto the player. Cannot convert UnityEngine.Object into System.Type, and the likes is what I keep getting. Does any of you lot know how to solve this? I'm posting it here as this is the first post I've found of at least a similar problem after an hour of searching. @LessThanEpic @Glurth @Mechlordx
Your answer
Follow this Question
Related Questions
clientRpc array of System.object loss object type and can't cast the objects 0 Answers
move another object when 2 other objects collide 1 Answer
Cannot cast from source type to destination type 1 Answer
Cast Vector3 to object 1 Answer
How to call a function from one class to another class? 2 Answers