Quantcast
Channel: Questions in topic: "javascipt"
Viewing all articles
Browse latest Browse all 1875

Dynamically adding Javascript to an Instantiated object using AddComponent,Using AddComponent to add a JS Monoscript Causes "NullReferenceException

$
0
0
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: ![alt text][1] 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? [1]: /storage/temp/154156-9aadb2d9a5cf7387c60d99e38e86b9ab.png

Viewing all articles
Browse latest Browse all 1875

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>