- Home /
Can't get var from other script.
I have two javascript scripts:
Force.js:
var power : float = 50.0;
var Mage : GameObject;
function Update () {
var other : PunchWall;
other = Mage.GetComponent("PunchWall");
Debug.Log(other);
/*if(other.punchOK==1){
rigidbody.AddForce(Vector3(power,0,0));
}*/
}
PunchWall.js:
var startpunch : float;
var punchOK : int = 0;
function Update () {
if(Input.GetButtonDown("Jump")) {
startpunch = 35;
punchOK = 1;
}
if(startpunch>0) {
animation.Play("punch");
startpunch--;
}
}
function OnTriggerEnter(theCollision : Collider){
if(theCollision.gameObject.name == "Hitbox"){
if (punchOK == 1) {
}
}
}
And I want to use the variable 'punchOK', which is stated in my 'PunchWall' script and is linked to my player named Mage. (Force is linked to my Brick, which is supposed to fly away after it gets punched.
I put a Debug in the Update and it gives 'Null'. So it doesn't even fill my var other?
Ok, maybe "other=GameObject.Find("$$anonymous$$age").GetComponent(PunchWall).punchO$$anonymous$$;" However, I'm still not sure about that, because I don't have Unity here, in this moment! Hope to help you, this time...
That's okay, I appreciate any help!
It does give an other error now though: "InvalidCastException: Cannot cast from source type to destination type."
Ah, yes: you are declaring other as "PunchWall",in Force.js, but the istruction that I've posted above returns an integer, now. Remove "var other : PunchWall" and declare "other" directly into the istruction above (var other=GameObject.Find....); or declare "other" as int.
Answer by aldonaletto · Sep 22, 2011 at 10:00 AM
You should do the following to get the punchOk value:
var power : float = 50.0;
function Update () { var other : PunchWall; other = GameObject.Find("Mage").GetComponent(PunchWall); Debug.Log(other); if (other.punchOK==1){ rigidbody.AddForce(Vector3(power,0,0)); } } But it seems the whole thing is wrong: the better way to do that would be to apply the force in OnTriggerEnter or OnCollisionEnter (depends on the brick's collider isTrigger flag).