Search Unity

Resolved Accessing public variables between scripts

Discussion in 'Scripting' started by WhoWantsTacos, Apr 20, 2023.

  1. WhoWantsTacos

    WhoWantsTacos

    Joined:
    Mar 8, 2020
    Posts:
    4
    Hello All!

    I am currently trying to work out how to access a particular variable stored in one script from another.

    I have a game object with the script: PlayerMovement as its component
    Code (CSharp):
    1. public class PlayerMovement : MonoBehaviour
    2. {
    3.     //working from video: https://www.youtube.com/watch?v=K1xZ-rycYY8
    4.     //declare variables
    5.     private float horizontal;
    6.     private float speed =8f;
    7.     private float jumpingPower =16f;
    8.     public bool isFacingRight = true;
    9.     private float angle;
    10.     //private float jumpExplodePower = 32f;
    11.  
    12.     //SerializeField
    13.     [SerializeField] private Rigidbody2D rb;
    14.     [SerializeField] Transform groundCheck;
    15.     [SerializeField] private LayerMask groundLayer;
    16.  
    17.  
    18.     // Update is called once per frame
    19.     void Update()//use inputs to call functions
    20.     {
    21.         horizontal = Input.GetAxisRaw("Horizontal");//returns a value of -1, 0, or 1
    22.  
    23.         if (Input.GetButtonDown("Jump") && IsGrounded())//if jump button is held, get the full jump power
    24.         {
    25.             rb.velocity = new Vector2(rb.velocity.x, jumpingPower);  
    26.         }
    27.  
    28.         if (Input.GetButtonUp("Jump") && rb.velocity.y > 0f)//if jump button is tapped, get a reduced jump power
    29.         {
    30.             rb.velocity = new Vector2(rb.velocity.x, rb.velocity.y*0.5f);
    31.         }
    32.         JumpExplode();
    33.     }
    34.  
    35.  
    36.     private bool IsGrounded()
    37.     {
    38.         return Physics2D.OverlapCircle(groundCheck.position, 0.2f, groundLayer);
    39.     }
    40.  
    41.     private void FixedUpdate()
    42.     {
    43.         rb.velocity = new Vector2(horizontal * speed,rb.velocity.y);
    44.     }
    45.    
    46.     private void JumpExplode ()
    47.     {
    48.         if(Input.GetButton("Fire1"))
    49.         {
    50.             //set the value of angle equal to the angle found from the reticle
    51.             //angle = ReticleBehavior.ReticleAngle ()
    52.             //set a new vector2 with the x and y components of jumpExplodePower
    53.             //rb.velocity = new Vector2(jumpExplodePower*Mathf.cos(angle), jumpExplodePower*Mathf.sin(angle));
    54.         }
    55.     }
    56.    
    57. }
    And another GameObject as the first one's child with the script: ReticleBehavior as its component
    Code (CSharp):
    1. public class ReticleBehavior : MonoBehaviour
    2. {
    3.     //Working from video: https://www.youtube.com/watch?v=-bkmPm_Besk
    4.  
    5.     private Camera mainCam;
    6.     private Vector3 mousePos;
    7.  
    8.     public float rotZ;
    9.  
    10.     // Start is called before the first frame update
    11.     void Start()
    12.     {
    13.         mainCam = GameObject.FindGameObjectWithTag("MainCamera").GetComponent<Camera>();
    14.     }
    15.  
    16.     // Update is called once per frame
    17.     void Update()
    18.     {
    19.         ReticleAngle();
    20.     }
    21.  
    22.     public float ReticleAngle ()
    23.     {
    24.         //Find mouse position on the screen
    25.         mousePos = mainCam.ScreenToWorldPoint(Input.mousePosition);
    26.  
    27.         //store change between mouse position and gameObject position as vector3
    28.         Vector3 rotation = mousePos - transform.position;
    29.  
    30.         //get the angle in radians by using inverser tan of vector.y component over vector.x component and convert to degrees
    31.         rotZ = Mathf.Atan2(rotation.y, rotation.x) * Mathf.Rad2Deg;
    32.  
    33.         //rotate game object(and its children) by the angle found
    34.         transform.rotation = Quaternion.Euler(0,0,rotZ);
    35.  
    36.         //Debug.Log(rotZ);
    37.         return rotZ;
    38.     }
    39. }
    My question is why am I not able to see the public variables from the ReticleBehavior script in the IntelliSense Menu from VSCode when I am writing in the PlayerMovement script?
    Particularly in PlayerBehavior on line 51, I want to set the value of 'angle' to the value of 'rotZ'(from ReticleBehavior) but am encountering a script error with the line of code on line 51 that I am currently using.

    Any help would be appreciate and thank you for your time.
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,697
    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.

    Could be anything: namespacing, a typing mistake, intellisense taking a vacation, etc.

    This may help you with intellisense and possibly other Visual Studio integration problems:

    Sometimes the fix is as simple as doing Assets -> Open C# Project from Unity. Other times it requires more.

    Other times it requires you also nuke the userprefs and .vsconfig and other crufty low-value high-hassle files that Visual Studio tends to slowly damage over time, then try the above trick.

    Barring all that, move on to other ideas:

    https://forum.unity.com/threads/intellisense-not-working-with-visual-studio-fix.836599/

    Also, try update the VSCode package inside of Unity: Window -> Package Manager -> Search for Visual Studio Code Editor -> Press the Update button

    Also, this: https://forum.unity.com/threads/no-suggestions-in-vscode.955197/#post-6227874
     
    WhoWantsTacos likes this.
  3. kdgalla

    kdgalla

    Joined:
    Mar 15, 2013
    Posts:
    4,635
    ReticleBehavior.ReticleAngle () doesn't make sense because ReticleBehavior is a type, not a specific object. It's like saying "Give me page 57 of book." Which book? There are a million different books. There could be lots of ReticleBehaviors too.

    So you need to get a reference to the specific ReticleBehavior that's on that specific object. There are several ways to do this, but the easiest is probably to add a member variable, like:

    public ReticleBehavior playerReticleBehavior;

    Then, in the editor, you can just drag the object with the ReticleBehavior into the slot.
     
    Last edited: Apr 21, 2023
  4. WhoWantsTacos

    WhoWantsTacos

    Joined:
    Mar 8, 2020
    Posts:
    4
    Thank you Kurt-Dekker, and thank you kdgalla using both of your responses I can now reference my ReticleBehavior script inside of my PlayerMovement script.
     
    Kurt-Dekker likes this.