how can I have a game object get a variable from a different object with collision
so i have a basic player and when the hit a pick up (health or damage) I want then to get the value or val variable off the object to pass into this function on there script
void OnCollisionEnter(Collision other) {
//if (other.gameObject.CompareTag ("Damage")) {
if (other.gameObject.name=="Damage"){
//GameObject timp= other.collider.gameObject.GetComponent (HP_Val);
HP_fill.fillAmount = HP.SetHP (**"How do I get Val here?"**);
HPtext.text = HP.desplay_HP;
//Destroy (other.gameObject);
if (HP.Helth == 0)
{
m_Animator.SetBool("KO", true);
}
}
}
I know this is do able but what am I missing?
Answer by HenryStrattonFW · Jan 20, 2017 at 11:46 PM
lets assume that your damage/health pack classes are called "DamagePack" and "HealthPack" and each has a public variable called "value". Here is how you could test for and get those variables.
// Try to find components on the object.
HealthPack lHealthPack = other.gameObject.GetComponent<HealthPack>();
DamagePack = lDamagePack = other.gameObject.GetComponent<DamagePack>();
if (lHealthPack != null)
{
// you have a health pack just use lHealthPack.value to increase health.
}
if (lDamagePack != null)
{
// you have a damage pack just use lDamagePack.value to decrease health.
}
well that did help its not giving me an error wen i try to pass temp.Val into setHP
void OnCollisionEnter(Collision other) {
//if (other.gameObject.CompareTag ("Damage")) {
if (other.gameObject.name=="Damage"){
HP_Val temp= other.collider.gameObject.GetComponent (HP_Val);
//int x= temp
HP_fill.fillAmount = HP.SetHP (temp.Val);
HPtext.text = HP.desplay_HP;
//Destroy (other.gameObject);
if (HP.Helth == 0)
{
m_Animator.SetBool("$$anonymous$$O", true);
}
}
}
I do have a different error that is probably me just over looking something obvious
Assets/script/characterController.cs(99,57): error CS0118: HP_Val' is a
type' but a `variable' was expected
This is because your type is (im assu$$anonymous$$g) HP_Val but when you're trying to use GetComponent you have to do it in certain ways. you can either use the type name as a string "HP_Val" as a System.Type "typeof(HP_Val)" or as a generic "GetComponent()" note the angle brackets in that last one.
https://docs.unity3d.com/ScriptReference/GameObject.GetComponent.html
The documentation of the GetComponent method should help clear this up and get you back on track.
Your answer
Follow this Question
Related Questions
Assigning Values In Start () That Will Change 1 Answer
Ray-cast only detecting tags in debug.log and not in a if statement 0 Answers
Line renderer how to create and edit 1 Answer
How to use the predefined syntax in monodevelop quickly ? 1 Answer
How can I get this code to recognize coll in my update function? 1 Answer