- Home /
Custom class and null reference exception
Hello there. I have a problem with a custom created class. This is the tEnemy.js script.
class tEnemy
{
var gameobj:GameObject;
var hp: int;
function create()
{
gameobj = GameObject.CreatePrimitive(PrimitiveType.Cube);
}
}
Now when in the main script i try to create some tEnemies:
var ob: tEnemy;
ob.create();
ob.gameobj.AddComponent(Rigidbody);
ob.gameobj.transform.rotation.x = Random.value;
ob.gameobj.transform.rotation.y = Random.value;
ob.gameobj.transform.rotation.z = Random.value;
ob.gameobj.transform.localScale = Vector3 (enemySize, enemySize, enemySize);
ob.gameobj.transform.position.x = -2+Random.value*6;
ob.gameobj.transform.position.z = -3.4+Random.value*6;
ob.gameobj.transform.position.y = 2;
ob.hp = 4;
I get a NullReferenceException and nothing happens. Please help me, what am i doing wrong?
Answer by syclamoth · Apr 16, 2012 at 05:41 AM
This happens because the line
var ob : tEnemy;
Only creates a 'tEnemy' shaped hole, that can have a tEnemy object put in it at a later state- it doesn't create the object itself! The expression
new tEnemy();
creates an object, but without a slot to put it in it's not much use to you. This is why the two lines are usually written together, like so:
var ob : tEnemy = new tEnemy();
This crates the slot, and simultaneously fills it with an object.
I see that you are using an initialisation function, 'create' in your custom class. Consider using the constructor for this, so that you only need to use the 'new' statement, without calling 'create' seperately!
// Put this in the tEnemy class, and it will be called
// every time you create one!
function tEnemy()
{
create();
}
Answer by aviose · Apr 16, 2012 at 05:33 AM
I had a lot of issues with a similar, but more deeply embedded version of this error. If you want to actually alter the member properties of the class, then simply telling the variable it is of type:class doesn't work. You HAVE TO establish the object with an explicit declaration... To draw it out, your first line on your enemy creation should read:
var ob: tEnemy = new tEnemy();
If you don't use that format, with the var fu : class = new class(); format, it will give you all sorts of null errors.
(When I got the error it was because I had stats that broke down in to smaller versions, like current/max or base/modValue. I declared the base object properly but not the modValues/base aspect of the stats. Since Unity Editor doesn't tell you where to really look for these errors it took me FOREVER to find the solution.)