Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice

Question is it possible to take one variable from one script to another?

Discussion in 'Scripting' started by ItsMe1423, Apr 2, 2024.

  1. ItsMe1423

    ItsMe1423

    Joined:
    Sep 23, 2020
    Posts:
    78
    I want to take the Players from a script where it is set like this:
    Code (CSharp):
    1.     public List<Player> Players = new List<Player>();
    2.  
    to a different script, how do I do it?
     
  2. LaneFox

    LaneFox

    Joined:
    Jun 29, 2011
    Posts:
    7,566
    You need a reference to the other script, usually from setting it in the Inspector where public fields are available for drag-n-drop.

    Code (csharp):
    1. public class FirstScript : MonoBehaviour
    2. {
    3.     public List<Player> Players = new List<Player>();
    4. }
    5.  
    6. public class OtherScript : MonoBehaviour
    7. {
    8.     public FirstScript Reference; // assign this in the inspector
    9.  
    10.     public void Start()
    11.     {
    12.          foreach (var x in Reference.Players)
    13.          {
    14.              Debug.Log(x);
    15.          }
    16.     }
    17. }
     
    Last edited: Apr 2, 2024
  3. ItsMe1423

    ItsMe1423

    Joined:
    Sep 23, 2020
    Posts:
    78
    it gives me This error on the semi-colon:
    CS1519 Invalid token ';' in class, record, struct, or interface member declaration
     
  4. zulo3d

    zulo3d

    Joined:
    Feb 18, 2023
    Posts:
    1,054
    LaneFox posted two scripts in one code box which understandably confused you.

    You already have your script containing your Players list and so you can reference the list from another script like this:
    Code (CSharp):
    1. using UnityEngine;
    2. public class Potato : MonoBehaviour
    3. {
    4.     public PlayersScript ps; // Use the editor to drag the script that contains your Players list onto this field
    5.  
    6.     public void Start()
    7.     {
    8.         foreach (var x in ps.Players) // Get each Player from the Players list
    9.         {
    10.             Debug.Log(x);
    11.         }
    12.     }
    13. }
    Note: Replace PlayersScript with the actual name of the script that contains your Players list.
     
    Last edited: Apr 2, 2024
  5. ItsMe1423

    ItsMe1423

    Joined:
    Sep 23, 2020
    Posts:
    78
    oh ok tnx