- Home /
How to add an object to a MonoBehaviour in JavaScript?
I have a CharacterController for a simple monster AI, and I have a separate class for an A* pathfinding implementation. I'm hoping that I could attach an instance of the A* class to the monster, but I keep getting the following error: "NullReferenceException: Object reference not set to an instance of an object"
I'm hoping to have the A* instances for every monster, since they all need to find their paths around the level and for performance reasons the pathfinding is propagated across multiple frames (my levels are huge randomly generated dungeons).
Since Unity's JavaScript implementation doesn't seem to have the features that I'm used to, I'm quite stumped - I couldn't find any good examples on how to do this either. Is it even possible with JavaScript, or should I start looking at C#?
@Lynchpin, glad it helped - feel free to use the handy checkmark symbol below. :)
Answer by Cyclops · Jun 28, 2010 at 04:02 PM
Javascript files in Unity automatically inherit from MonoBehavior, so yes, it does have that feature, you don't need to use C# (although I prefer C# :)
I'm not sure what steps you have taken, but starting from the beginning - once you have a JS script somewhere in the Assets directory (should see it in the Project view), then it is a Component, and needs to be attached to a GameObject. So if you have a Monster GameObject in your Scene, you would just drag/drop the script to it.
Once it's attached, then you have to make sure the script is properly referencing the Monster GameObject, depending on what you want to do. For instance, if you wanted it to move forward, you could say something like:
transform.position.x += 20;
Since the script is now a Component of the GameObject, that line references the GameObject's Transform.
If that doesn't help, then could you edit your Question to indicate what variable is getting a NullReferenceException?
Oh wow, it worked! I guess I just thought about it in an over-complicated manner; I'm used to instancing classes as member variables and I'm still a novice when it comes to Unity.
Thank you!
@Lynchpin, yeah, Unity is powerful, but it does take a different $$anonymous$$dset (which I'm still working on). For instance, any public variables in your script - can be edited at runtime in the Editor. So you can tweak variables while the project is running, until the numbers are right (although you have to set them in the script, once you leave runtime everything resets).