Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Change variable of script2 in script1

Discussion in 'Scripting' started by plapi, Apr 18, 2019.

  1. plapi

    plapi

    Joined:
    Apr 18, 2019
    Posts:
    6
    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)
     

    Attached Files:

  2. Tarodev

    Tarodev

    Joined:
    Jul 30, 2015
    Posts:
    190
    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:
    Code (CSharp):
    1.   var controller = FindObjectOfType<PlatformerCharacter2D>();
    2. controller.speed += speedPotionValue;
    2. The above script can be made more efficient by creating a static instance of the player like so (in the controller script):
    Code (CSharp):
    1. public static PlatformerCharacter2D Instance;
    2. private void Awake() {
    3.        Instance = this;
    4. }
    Now any object can easily access the player like this:
    Code (CSharp):
    1. PlatformerCharacter2D.Instance.speed = potionValue
    3. You can use Gameobject.SendMessage():
    Code (CSharp):
    1. void OnTriggerEnter2D(Collider2D collision){
    2.         if (collision.tag == "Player") {
    3.             collision.gameObject.SendMessage("AddSpeed", speedPotionValue);
    4.         }
    5.     }
    And in your player script:
    Code (CSharp):
    1.  
    2. public void AddSpeed(float value) {
    3. Speed += value;
    4.     }
     
  3. plapi

    plapi

    Joined:
    Apr 18, 2019
    Posts:
    6
    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
     
    Tarodev likes this.