Change variable of script2 in script1

Hello Community.

yesterday I was trying to speed up my character when triggering another object (in my case it’s a bottle).

So far, I can output a Hello World, I can output a variable (int) (script with variable (int) on Character, output script on bottle).

So, I can output the speed of my character, but how can I change it?

I am happy about any help.

Unity 2018.3.6f1 Personal
(2D game, attached scripts: PlatformerCharacter2D.cs = script on CharacterRobotBoy
speedPotion = script on my bottle)

4444177–406969–PlatformerCharacter2D.cs (5.09 KB)
4444177–406978–speedPotion.cs (386 Bytes)

There is a range of ways to handle this, let me name a few:

  1. Grab a reference of the player in the potion script when colliding with player like so:
  var controller = FindObjectOfType<PlatformerCharacter2D>();
controller.speed += speedPotionValue;
  1. The above script can be made more efficient by creating a static instance of the player like so (in the controller script):
public static PlatformerCharacter2D Instance;
private void Awake() {
       Instance = this;
}

Now any object can easily access the player like this:

PlatformerCharacter2D.Instance.speed = potionValue
  1. You can use Gameobject.SendMessage():
void OnTriggerEnter2D(Collider2D collision){
        if (collision.tag == "Player") {
            collision.gameObject.SendMessage("AddSpeed", speedPotionValue);
        }
    }

And in your player script:

public void AddSpeed(float value) {
Speed += value;
    }

Thank you so much! I used the 3. way to do it, very easy… I could’ve figured that out myself, but thank you anyway

1 Like