Search Unity

Question How can I pass on the variable from another script to another?

Discussion in 'Scripting' started by rafoskiki, Mar 13, 2023.

  1. rafoskiki

    rafoskiki

    Joined:
    Jan 25, 2023
    Posts:
    12
    Hello, just in case, yes im new to unity and blablabla,anyways
    what I need is a way for this script to know if my player has the isGP variable active and then destroy whatever thing it needs (if y'all need the movement script I can give it)

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;

    public class TESTBreak : MonoBehaviour
    {
    [SerializeField] private Transform BreakCheck;

    public void Start()
    {
    gameObject.Find("player").GetComponent<playerMovement>().NameOfTheProperty = isGP;
    }
    private void OnTriggerEnter2D(Collider2D collision)
    {
    if(collision.tag == "Player")
    {

    }
    while (IsGP == true)
    {
    Destroy(GetComponent<SpriteRenderer>());
    Destroy(GetComponent<BoxCollider2D>());
    }
    }


    }
     
  2. D12294

    D12294

    Joined:
    Oct 6, 2020
    Posts:
    81
  3. rafoskiki

    rafoskiki

    Joined:
    Jan 25, 2023
    Posts:
    12
    I believe this is not what I need, but I appreciate the gesture!
     
  4. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,745
    Referencing variables, fields, methods (anything non-static) in other script instances:

    https://forum.unity.com/threads/hel...-vars-in-another-script.1076825/#post-6944639

    https://forum.unity.com/threads/accessing-a-gameobject-in-different-scene.1103239/

    REMEMBER: it isn't always the best idea for everything to access everything else all over the place. For instance, it is BAD for the player to reach into an enemy and reduce his health.

    Instead there should be a function you call on the enemy to reduce his health. All the same rules apply for the above steps: the function must be public AND you need a reference to the class instance.

    That way the enemy (and only the enemy) has code to reduce his health and simultaneously do anything else, such as kill him or make him reel from the impact, and all that code is centralized in one place.

    Be sure you understand what you mean by "pass on the variable" because it makes a HUGE difference:

    Value Types vs Reference Types:

    https://forum.unity.com/threads/hel...a-game-object-with-code.1047332/#post-6779456
     
  5. Homicide

    Homicide

    Joined:
    Oct 11, 2012
    Posts:
    660
    Also - see the Code<> button on the menu where you are typing, put your code in there please. Cheers.
     
    rafoskiki likes this.