I have three classes: a Main, a Player and a Car.
The main creates a Car and a Player.
The Car needs to trace the player’s x position.
But the code below is not working. I have researched and found that declaring it as static should fix the problem although it is not the best way to do it?
Main:
package {
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.MouseEvent;
public class Main extends MovieClip
{
public static var _player:Player;
public static var _car:Car;
public function Main()
{
createPlayer();
}
public function createPlayer():void
{
_player= new Player();
_car = new Car();
_player.x = stage.stageWidth / 2;
_player.y = stage.stageHeight / 2;
stage.addChild(_player);
stage.addChild(_car);
}
}
}
Car:
package {
import flash.display.MovieClip;
import Main;
public class Player extends MovieClip
{
public function Player()
{
trace(Main._car.x);
}
}
}
But this causes an error:
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at Player()
at Main/createPlayer()
at Main()
I want to know why this is giving me an error and what are the other good ways to do this?
//EDIT: Sorry _hero was my mistake, it is actually _car.
Thank You Very Much………..
First of all: THIS IS NOT A RIGHT WAY TO PROGRAM! You shouldn’t be using static properties everywhere.
Secondly: Your _player instance is created before you assign
new Car()to your _car instance, that’s why it’s still null. Try changing their lines, so that you have:Again, this will solve your problem, but your coding is not the right way. If you want to have a reference to your _car object, pass it in Player class’ constructor.
P.S. Don’t forget to mark this post as an answer if it helped you.
EDIT:
Here is some code to get you started:
In your Player class add a private property for storing a reference on your Car object. Then add your Player’s constructor a parameter, which you will pass when creating a new Player. Note that use this only if you want to store a reference to your Car object in your Main class too.
When defining a Player object, you’ll now need to pass in your Car object to it’s constructor. So do it like this:
IF you don’t need a reference to your Car object in your Main class, or better to say if a Car is assigned to a Player, so that each Player would have it’s own Car, you’d better define a property in your Player Class, like this:
Also note that this Car object we initialized in Player class can be accessed from you Main class like this:
I’d suggest you read basic concept of OOP (Object Oriented Programming), such as Encapsulation, Inheritance and Polymorphism. Search google for some good books which will help you get on your feet.