- Home /
Instantiate a class type from inside a variable?
Hi, I have a few Boss AI classes that inherit from the class Boss.
In inspector, I can drag in a BossAI script as an object (BossClass), but I'm not able to properly instantiate it.
this compiles but throws this error: "NullReferenceException: Object reference not set to an instance of an object"
Answer by Bunny83 · 4 days ago
You can not drag script assets onto variables. Well you can because the Unity editor uses a special class in editor code called MonoScript which is actually a TextAsset. That's what you have assigned to your "Object" variable. You have not assigned an instance of the class which may be defined inside that script file, but the script file itself.
Note that the MonoScript class is an editor only class. So you can not serialize a reference to a MonoScript inside a runtime class. The GetClass method of the MonoScript class actually returns the System.Type object of the class that may be implemented inside that script file. Though, again, this class can only used in editor code. See my answer over here for how to implement a property drawer that allows you to drag script assets onto the field and just have the type name stored.
Your answer

Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Accessing local system ( File Browser ) 2 Answers
System.Data and System.Data.SqlClient 1 Answer
ECS - System seems to only affect transform on first frame 1 Answer
Organizing Enemy Movement Types 0 Answers