- Home /
Accessing variable from a method in another script and gameObject
Hello. I know this question is kinda basic, but searching through the internet I can't really seem to find an answer. What I want, is to grab a variable from a public method ("public void FireBullet()") in another script from another gameObject. Without the variable being set outside of the method. Because I know that i can access these variables like this: Derp d = (Derp)GetComponent("Derp");
So a visual example of what I want kinda looks like this:
Derp d = (Derp)GetComponent("Derp")
//this is what my brain is thinking (syntactical facepalm, though):
hpLost = d.FireBullet().damageDealt
Any enlightenment here would be greatly appreciated. I've stumbled across this before, and I just had to resort to finding a way to use it as a public variable outside of the method, but it seems like overwork, the list of public variables outside of the methods will get very big.
Answer by Baste · Nov 06, 2014 at 01:20 PM
This:
d.FireBullet().damageDealt
Makes no sense. That's not how syntax works. If the FireBullet method returns a float value, then you do
hpLost = d.FireBullet();
If d saves damageDealt as a public variable after the bullet is fired, you do this:
d.FireBullet();
hpLost = d.damageDealt;
I still can't understand how to access "damageDealt" from the FireBullet() method in the other script.
using your
d.FireBullet();
hpLost = d.damageDealt;
it can't find damageDealt. Sorry for being so confused, and nooblike.
The vartiable has to be defined outside of the method. Variables defined inside the method are forgotten between each call to the method.
@Linus, so you are saying I shouldn't try to call variables defined in methods from another script?
Answer by Mayank Ghanshala · Nov 06, 2014 at 02:01 PM
First You can call Variables on class object only or a static reference of class . Second if you are making a variable inside a method means it is local to that and its scope will be only in that Function.You should consider these are some basic points of progarmming. What you can do you can make that A data type something like this
public float damageDealt{get;private set;}
then call it as usual
`hpLost = d.damageDealt`
What if I want the variable damageDealt to be specific? Can I do this outside of a function?
I know this is also coded wrong, but you get what I want to do here:
public float damageDealt() {
attackDamage += Random.Range(2,6);
}
Well, yes.. But, how would I do it any other way? I'm just spit-balling my bad ideas, to try and assist you in helping me, haha.
Your answer
Follow this Question
Related Questions
Variable Not Changing In Method 1 Answer
How to access gameObject variable script 2 Answers
Accessing Variable from another Script.. with a twist 2 Answers
Why the variable don't change your value? 1 Answer
[C#] Assets/BreakObject.cs(20,62): error CS0165: Use of unassigned local variable `broken' 1 Answer