Reputation: 121
Okay, so first, I have searched for this everywhere but it seems like every answer is either overcomplicated or simply does not work, and I know for sure there should be a more simple way of achieving what I need.
So, until today, I have always coded from within the timeline. But now I realise why I should code in separate class files. However, I still want to include snippets of code in the timeline for simplicity's sake.
So in my Ship class I have this line of code:
public var speed:int = 2 + Math.ceil(Math.random() * 4)
And in my timeline I have the code:
import Ship;
trace(Ship.speed)
I can't get the trace to display the speed. The class file executes perfectly on its own but when I try to access its speed variable (as above in the timeline), I get this:
Scene 1, Layer 'Actions', Frame 1, Line 2 1119: Access of possibly undefined property speed through a reference with static type Class.
So a simple question, and apologies for it, but can anyone give me a simple way to trace the speed from the Ship.as class file?
Thanks in advance!
Upvotes: 0
Views: 1613
Reputation: 4434
inside your Ship
class:
public function get speed():int{
return 2 + Math.ceil(Math.random() * 4);
}
and on the timeline:
import Ship;
var ship:Ship = new Ship();
trace(ship.speed);
Upvotes: 0
Reputation: 5693
You need to create a Ship instance, like this:
import Ship;
var ship:Ship = new Ship();
trace(ship.speed);
OR
You can declare speed as a static variable to access it without the need of an instance (but I think here it makes less sense):
public static var speed:int = 2;//or whatever
To learn more about static variables and methods in AS3, check this response: Actionscript 3: Can someone explain to me the concept of static variables and methods?
Upvotes: 2