- Home /
How to change a variable from another script
I have a gorgon enemy unit that has an invisible trigger space that acts like the gorgons vision. I want it to reduce the players speed. I have got it to detect the player, but the only way I could find to access the variable is as static which defeats the purpose of changing the value. Is there a better way to access variables? Also I have used a public static class general to access it but not change it.
Answer by aardappel156 · Jan 11, 2019 at 06:22 PM
why can't you change the variable if it is static? It should be possible.
If you want a different way you could use the ontrigger function maybe something like this
PlayerScript myPlayerScript
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("Player"))
{
myPlayerScript = other.GetComponent<PlayerScript>();
myPlayerScript.speed = 5;
}
}
void OnTriggerExit(Collider other)
{
myPlayerScritpt.speed = 10;
}
You do NOT need PlayerScript myPlayerScript
You can access the player's script from within the trigger functions. There's no need to create a member variable.
private void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Player"))
{
var player = other.GetComponent<PlayerScript>();
player.speed = 5;
}
}
void OnTriggerExit(Collider other)
{
if (other.CompareTag("Player"))
{
var player = other.GetComponent<PlayerScript>();
player.speed = 10;
}
}