So im trying to change a variable in another script by touching a cube. Current setup
- 1x Player
- 1x Enemy
Each with their own script Enemy_Stats
& Character_Stats
As you can see in this little snippet it's quite a workaround to access the variable from another script.
void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.tag == "Enemy")
{
collision.gameObject.GetComponent<Enemy_Stats>().Health =
collision.gameObject.GetComponent<Enemy_Stats>().Health
- gameObject.GetComponent<Character_Stats>().AttackDamage;
if (collision.gameObject.GetComponent<Enemy_Stats>().Health <= 0)
{
Destroy(collision.gameObject);
}
}
}
Iam new to Unity, but isn't there a way to just refer it with something like:
collision.Health
?
No since
Health
is not part of the collision object, butEnemy_Stats
. You can cache aComponent
(that's what Enemy_Stats is) if you use it multiple times to save you some typing (and some performance, but that is rather marginal for this example). Also you can cache "known" components like in this casePlayer_Stats
. You can do this e.g. inStart
or with a public variable and the inspector.What you should probably do though is to make the enemy be responsible for his life and not the player, so move the
Destroy
-part toEnemy_Stats
(into the Health property to be exact).The first thing to make this shorter (and eventually faster) would be to store this:
gameObject.GetComponent<Character_Stats>()
onStart()
in a private variable (you should avoid calling GetComponent on a frequent basis if you can avoid it).For the Health variable, a way of avoiding
GetComponent
calls could be caching: you create aDictionary<GameObject, Enemy_Stats>
and read from that as soon as this gameobject collided onceHow to access variables/functions from another Class. The variable or function you want to access or called must be
public
notprivate
.Access variable
playerScore
inScriptA
fromScriptB
. First, find the GameObject that the script or component is attached to with theGameObject.Find
function then use theGetComponent
function to retrieve that script or component that is attached to it.