Dynamically adding Javascript to an Instantiated object using AddComponent,Using AddComponent to add a JS Monoscript Causes "NullReferenceException
I recently upgraded an old unfinished project (please excuse any terrible code - I wrote it in college), and I'm trying to root out all the bugs. One that has tripped me up immensely is a bug involving "AddComponent"
function Awake(){
p1 = Instantiate(GlobalHandlerScript.tempPlayer1); //instantiate player
p1 = p1.AddComponent(ControllerScript) as MonoScript; //Add controls
Debug.Log("p1");//test
p1 = p1.AddComponent(PlayerStats) as MonoScript;
Debug.Log("end p1");//test
}
As you can see in this codeblock, I instantiate a player object and add a script for the player's controls, and then the player's stats. Both of these scripts are located in Assets/Resources.
When I run this project, I get the following results on the console:
It looks like the project successfully loaded ControllerScript, but then fails to load PlayerStats from the same location, in the same way.
If I try to remove the "p1 =" and run it as p1.AddComponent(ControllerScript) as MonoScript;, I get the "Expressions in statements must only be executed for their side-effects".
What is the proper way to apply a script to a dynamically instantiated game object?