- Home /
Problems with Classes...i think
Yeah, so I'm just trying to grasp the concept of classes, so bear with me.
I have these lines of code in my scripts. I want to make a class of gun attributes called Gun. Then I want to make a variable of "guns" which is a Gun class. I can put as many different guns' attributes in the variable as I want. Then I will use a simple number variable to designate which one to use.
class Gun
{
var fireRate : float; //Bullets per second
var range : float;
var damage : float;
var clipSize : int;
var maxBullets : int;
var bulletsLeft : int;
var bulletsStored : int;
}
var guns : Gun[];
var currentGun : Gun = guns[currentGunNum];
The problem is I keep getting a "NullRefException: Object Reference not set to an instance to an instance of an object". I have filled up the "guns" variable with 2 elements of variables, but the currentGun variable is empty. I want currentGun to take on the attributes of what ever gun currentGunNum is.
If you guys need more of my script, you can find it here: https://dl.dropboxusercontent.com/u/33872519/PlayerBehavior.js
thanks for the help!
Answer by IgorAherne · Jul 21, 2013 at 09:57 PM
var guns : Array = newArray();
var _Gun1 : Gun = new Gun();
guns.Push(_Gun1);
if you need to reference _ Gun1 from your guns do this:
(guns[0] as Gun)
_Gun1 belongs to the Gun class, and such variable will contain specified variables in it. For example, lets get the 0th cell from guns (_Gun1) and then get fireRate of the _Gun1.
(guns[0] as Gun).fireRate = 12.0;
Всегда пожалуйста)
Ok, but then how would I reference other guns? Will I have to write separate code for each weapon?
if(Gun1 == true)
{
Gun1.fireRate = fireRate;
}
if(Gun2 == true)
{
Gun2.fireRate = fireRate;
}
Sorry, new to arrays and classes. What I was trying to do was something like this: http://answers.unity3d.com/questions/202191/spawn-n-enemies-every-nth-wave.html
I like having an dropdown menu of several guns attributes and then being able to access the variables by their number.
thanks for helping a confused soul!
guns is a "collection" of objects of class Gun.
But each gun object so far is just a collection of variables.
you can set the parameters of each gun in guns, like shown in the last line of my answer,
and you would be able to to plug in such value somewhere in Update, where the whole code would be.
Basically, Gun is like an array of 7 objects.
When we create an instance of class
var _Gun1 : Gun = new Gun();
we are creating an array-like thing. _Gun now holds 7 variables, and we can have many of _Gun objects in some kind of array, like guns
but _Gun is just a collection of variables which cary values at the moment.
You could also place a function in class Gun, and then every instance of such class would have a function, but so far u just have variables.