- Home /
Using a variable value with GetComponent
Hi to all! I'm working on a top-down shooter, and i'm doing good, but till now I didn't care about the code repetition, and I made 5 powerups with pretty much the same script, with some little differences. What I want to do now is to make a single script, who takes all the references it needs, and calls the right methods to apply the right powerup. To activate bonuses, I'm trying to use a simple code like this one:
public void BonusON(string bonusName)
{
bonusDuration = GameObject.FindGameObjectWithTag(bonusName)
.GetComponent<scriptName>.bonusDuration;
//other code
}
What i'm trying to do is to reproduce something I saw while I was learning PHP, like dinamically obtaining a variable name using another variable value, then use the variable name to call a different method I prepared before... I made a research online to find if this way could be used in c# as well, but without luck. What I surely need to know is if there's a way to use the GetComponent method as I wrote above, so giving it a variable and letting it use that variable value as a component name.
Or, if there's a simpler way, of course.
Answer by Eudaimonium · Sep 06, 2015 at 08:20 PM
Above code should work, except you're missing brackets for actual function call on GetComponent method:
bonusDuration = GameObject.FindGameObjectWithTag(bonusName).GetComponent<scriptName>().bonusDuration;
I would suggest against using "Find" functions within gameplay time, though, official docs say it's quite slow and can cause performance hiccups. Use any other method of obtaining a solid reference, for example if you're activating something while colliding with it, obtain the reference to the object via Collision argument.
Or if at all possible, use public variables and assign references via Inspector.
Yeah, my fault about the missing brackets... So, you're telling me that if scriptName is a string variable who have for value the tag of a gameObject, this syntax could work?
Yes, but like I said, avoid using "Find" functions. This will simply return the first GameObject with the corresponding tag. If there are multiple ones, any one could be returned. But syntax could theoretically work, yes.
Any particular reason why you aren't simply trying this out for yourself, see if it compiles and how it works, and ins$$anonymous$$d asking on the Answers first?
Well, to be honest, I tried before asking, but I thought I was making some mistake with syntax, because I was always getting a null value, or an error about a missing reference :P
Your answer
Follow this Question
Related Questions
Syntax troubles (GetComponent and changing variables) 1 Answer
Has my project's data corrupted? Script keeps returning null but 20 minutes ago it wasn't? 1 Answer
Calling variable accross scripts in C# problem (Closed) 1 Answer
Random selection 1 Answer
Getting a Variable on Script B to equal a variable from script A 0 Answers