- Home /
Variable Scope
Why is it that my variable "attack" has a scope that extends into the "Attack()" function, but my variable "target"'s scope does not reach into the "GetTarget()" function? Just curious.
using UnityEngine;
using System.Collections;
public class MonsterAI : MonoBehaviour
{
public string name = "NoName";
public GameObject target = null;
public float hp = 100f;
public float attack = 10f;
public float speed = 100f;
public float team = 1f;
public float action_bar = 0f;
void Start()
{
}
void Update()
{
//ticking down their action bar
if (action_bar < 100f)
{
action_bar += speed * Time.deltaTime;
}
else
{
target = GetTarget ();
Attack ();
Debug.Log (name + " has ended their turn.");
target = null;
action_bar = 0f;
}
//death
if (hp <= 0)
{
Destroy (gameObject);
}
}
//functions
GameObject GetTarget()
{
GameObject[] target = GameObject.FindGameObjectsWithTag("Monster");
return (target[0]);
}
void Attack()
{
string target_name = target.GetComponent<MonsterAI>().name;
float damage = Mathf.Round(Random.Range (attack - (attack * .1f), attack + (attack * .1f)));
target.GetComponent<MonsterAI>().hp -= damage;
Debug.Log (name + " attacks " + target_name + " for " + damage + "damage.");
}
void Dodge()
{
}
}
Answer by whydoidoit · Oct 02, 2013 at 05:03 AM
It's because you are also defining a variable called "target" in GetTarget which hides the one from the outer scope.
Ah so I can "mask" a variable with another variable? That does sound like bad practice though, would you guys agree? Seems like it would be confusing to whomever picked up my code.
Generally speaking it's very confusing, so you should avoid it. If you use Visual Studio and Resharper it complains a lot about it and points it out to you.
You could choose longer variable names, which helps self document the code (and given intellisense is a lot less typing than you might imagine).
"Ah so I can "mask" a variable with another variable?" - yes, simply never do it, it's that simple. You're fortunate to have @whydo answer a question, everyone else here is drunk :)
Answer by himanshugupta159 · Jan 25, 2019 at 07:36 AM
Written a blog related to the question which gives the indepth information related to varible scope. link:https://unfragilecoding.blogspot.com/2019/01/variable-scope.html