- Home /
Collection Using "GetComponent"
I am trying to create a script that allows the player to collect power ups. When the player collides with this powerup, I want a variable on a script attached to the powerup to turn to true ("Collected"). The rest of the code works fine, but on the "GetComponent" line I get the error is "The best overloaded method match for "UnityEngine.GetComponent(System.Type)" has some invalid arguments". Anyone know what this means and how to fix it? Thank you in advance!
void OnTriggerEnter (Collider hit)
{
if(hit.gameObject.tag == "Weapon")
{
if(Inventory.Instance.HCisUnlocked == false)
{
Inventory.Instance.HCisUnlocked = true;
//Turn off the Collider
hit.collider.GetComponent(TheScript).Collected = true;
Debug.Log("Collected PowerUp");
}
if(Inventory.Instance.HCisUnlocked == true)
{
WeaponStates.Instance.HC.Ammo += AmmoBoost;
hit.collider.GetComponent(TheScript).Collected = true;
}
}
}
Is Inventory a static class?? Please don't just ask "Why doesn't this code work?". You need to put some effort forth to give us the information we need in order to troubleshoot. I can't even test this given code because you haven't provided any of the scripts you are trying to access, or even the name of the class this code resides in. Please edit the question and be specific, we'll be happy to help.
Okay so I edited it for you, sorry that I didn't make it clear at the beginning it was stupid of me for someone to just see what the problem is. I am just not used to using GetComponent so I wondered if someone could tell me how to use it correctly in this case. Thanks!
Answer by clunk47 · Oct 02, 2013 at 08:09 PM
To use GetComponent in C# is a bit different than JS. For one, variables are private by default in C#, so you need to make Collected a public bool in your other script.
public bool Collected;
To access it from your other script, a minor difference from what you had:
hit.collider.GetComponent<TheScript>().Collected = true;
I thank you! Good explanation i'll keep this in $$anonymous$$d next time ill do something with get component :)