views:

19

answers:

2

how can i call public functions or vars of a sprite class from another class (or frame script)? i keep getting 1061: Call to a possibly undefined method getSide through a reference with static type flash.display:Sprite.

//Framescript
var a:Sprite = new customRect();
addChild(a);
a.getSide();

//.as file
package
{
import flash.display.Sprite;

public class customRect extends Sprite
{
public var side:Number;

private function customRect()
{
var box:Sprite = new Sprite();
box.graphics.beginFill();
box.graphics.drawRect(0, 0, 200, 200);
box.graphics.endFill();

side = box.width;
}

public function getSide():void
{
trace(side);
}
}
}
+1  A: 

You'll need to type the other class as whatever type of class it is. Sprite doesn't, by default, have whatever property you're trying to access, so you can't just do mysprite.myRandomVariableName. However, if you happen to know mysprite is really of type MyClass then you can do MyClass(mysprite).myRandomVariableName or (mysprite as MyClass).myRandomVariableName. When using the as keyword, note that the typed mysprite will evaluate to null if mysprite is not really of type MyClass. Trying to type mySprite to MyClass using the prior method will throw an error if mysprite is not of type MyClass.

Alternatively, I believe you can use square brackets to access a sprite's dynamic properties (i.e. mysprite['myRandomVariableName'], however it's really better practice to strongly type your objects.

//edit, since you posted a code sample:

All you need here is:

var a:CustomRect = new CustomRect();//note that since CustomRect is a class name, it should be captialized.
quoo
i honestly can not believe that this has been such a huge problem for me when all along it was this simple. thanks!
TheDarkInI1978
no prob:) it's not really all that clear from the documentation.
quoo
+1  A: 

Are you trying to call actual methods of the Sprite class or ones that you've added to a subclass of Sprite? My guess is that you need to cast the variable to the actual class that you are using. So instead of:

someReference.yourFunction();

you could try:

YourClass(someReference).yourFunction();

... this is only needed if you do not control the typing of someReference - if you do you can simply define it using var someReference:YourClass to make it known to the compiler that is is a var of YourClass type, and not of Sprite.

UPDATE after your code example was added, change:

var a:Sprite = new customRect();

to

var a:customRect = new customRect();

so the compiler knows it is a customRect and not a 'general' Sprite.

as an aside: it is custom to start classnames with an uppercase letter: so use CustomRect instead of customRect.

Simon Groenewolt