- Home /
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!
Answer by Maltus · Nov 01, 2010 at 05:14 AM
//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.
$$anonymous$$y 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?
Your answer
Follow this Question
Related Questions
Access variable from another script? Health! 3 Answers
Accessing a variable in one script from another script? (using C#) 1 Answer
Can I make variables visible to other scripts without making them visible in the Inspector? 1 Answer
Editing a variable from another script on collision 3 Answers
Is it possible to change a variable, into a script not assigned to any game object? 3 Answers