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()
{
}
}
It’s because you are also defining a variable called “target” in GetTarget which hides the one from the outer scope.
Written a blog related to the question which gives the indepth information related to varible scope.
link:Variable scope in Unity