Collision object and access to a script variable?

In a script that is tied to a prefab for an object I have the following:

function OnCollisionEnter(collision : Collision) { print(collision.gameObject.name); }

And this works fine, when my game is running on collision the colliding gameObject name is showing up in the status line.

I have a variety of gameObjects (instantiated prefabs) in my game and each prefab its own script.

Within each script I define 'var Alliance : int;'.

What I am having trouble with is in the OnCollisionEnter routine I want to access the Alliance variable that is in the script of the collision gameobject.

Since the script name that attaches to the gameObject varies (I name the script something different) what would be the syntax for me to access the Alliance variable?

essentially I want to do:

collisionObjectId = collision.gameObject."script name".Alliance;

but since the script name varies, what do I do here?

thanks for any help!

1 Answer

1
//yourscript.js
var Alliance : int;
function OnCollisionEnter(collision : Collision) 
{ print(collision.gameObject.name); 

var hitAllianceint : int = collision.gameObject.GetComponent(yourScript).Alliance;
print(hitAllianceint.ToString());
}

this should work

Thanks but this doesn't appear to answer my question. In you example I must replace 'yourScript' with the name of the script. Yes. My issue is that the colliding gameObject can have different script names. For example, I call the script that is attached to a enemy ship 'Enemy_AI.js'. I call the script that is attached to an enemy bullet 'Enemy_bullet.js'. Both of these will have a variable Alliance. The object whose OnCollisionEnter() is being called is the player ship which could be colliding with an enemy ship or an enemy bullet. What am I missing here?

You need to specify the function you want to call on those objects in an interface. So you have the function "int GetAlliance();" in an interface. Then your different scripts (bullet, ship) need to implement that interface. This looks like: "public class Enemy : iAttackingObject", where iAttackingObject is the name of the interface. When you have that, you can do this: int allianceInt = collision.gameObject.GetComponent(iAttackingObject).GetAlliance(); Is that what you want?