- Home /
how I can get a property of a GameObject?
I put a script component, with a proprietary life, how I can obtain and modify the initial value from another object that collided with it?
Thank you very much.
Answer by ckfinite · Jun 10, 2011 at 01:16 PM
What you could do this in the object that hits the other object:
function OnCollisionEnter(coll : Collider) {
if (coll.gameObject.GetComponent(NameOfOtherScript) != null)
coll.gameObject.GetComponent(NameOfOtherScript).YourProperty;
}
It does not work, I am trying to access the property and I always get an error that says life is not property in the class GameObject. I created my property so, public int life = 100, and the script is called PlayerSettings, but does not work, so I'm also trying to create public static int PLAYERLIFE = 100, but neither worked.
Please post your exact code. The only things I can think of are related to syntactical problems.
Answer by Joshua · Jun 10, 2011 at 01:14 PM
I'm not sure I understand your question, but I think you're meaning to ask how do I, from a script attached to gameObject A modify a variable in a script on component B when B collides with A?
If B has a rigidbody, when upon collision the OnCollisionEnter function will be called.
function OnCollisionEnter( enter : Collider ){
if( enter.gameObject == (gameObject_B)//you could also compare tags, or some other property to identify B
enter.gameObject.GetComponent( name_of_the_script_you're_accesing ).name_of_the_variable_;
}
}
It does not work, I am trying to access the property and I always get an error that says life is not property in the class GameObject. I created my property so, public int life = 100, and the script is called PlayerSettings, but does not work, so I'm also trying to create public static int PLAYERLIFE = 100, but neither worked.
Actually, I made a stupid mistake. The variable "enter" contains the Collider, not the gameObect. So ins$$anonymous$$d of enter.GetComponent... you want to use enter.gameObject.GetComponent...
Your answer
![](https://koobas.hobune.stream/wayback/20220612102442im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How can I access other scripts and their functions? 3 Answers
Can't find gameobjects being spawned getting a nullreferenceexception 1 Answer
Set variable in script from a different script... 3 Answers
Disable/Enable Script or Add/Remove? 1 Answer
Change position of GameObject between unity3d and eclipse 0 Answers