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

Question how to get value of list items from different script

Discussion in 'Scripting' started by Only4gamers, Jul 9, 2020.

  1. Only4gamers

    Only4gamers

    Joined:
    Nov 8, 2019
    Posts:
    327
    Hello everyone,
    How to get values of list of items from different script?
    there is a list of four elements containing all players position in a race. Element 0 is player position and other Elements are AI players position and positions are updating during race whole time. this is the script which creating this list (If this can help):

    Code (CSharp):
    1. // Description : LapCounter.cs : Use to calculate and display on screen laps and position for each car.
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using UnityEngine;
    5. using System;                                                                                                 //This allows the IComparable Interface
    6. using UnityEngine.UI;
    7. using UnityEngine.SceneManagement;
    8. #if PHOTON_UNITY_NETWORKING
    9. using ExitGames.Client.Photon;
    10. using Photon.Realtime;
    11. using Photon.Pun.UtilityScripts;
    12. using Photon.Pun;
    13. #endif
    14.  
    15.  
    16. public class LapCounter : MonoBehaviour {
    17.  
    18.     public Game_Manager                                         gameManager;                                // Access the Game_Mananger component
    19.     public bool                                                 SeeInspector = false;                        // use on custom editor to see all the variables
    20.     public bool                                                    b_Pause = false;                            // use for pause Mode
    21.     public Color GizmoColor = new Color(1,.92f,.016f,.5f);                                                    // Gizmo color for the la counter gameObject
    22.  
    23.     public bool                                                    b_ActivateLapCounter = true;                // if true : the Lap Counter is activated
    24.     public int                                                    lapNumber = 3;                                // know the number of lap in a race
    25.  
    26.     public List<CarPathFollow>                                     car = new List<CarPathFollow> ();            // access CarPathFollow componentn for each car
    27.     public List<CarController>                                     carController = new List<CarController> ();    // access CarController component for each car
    28.     public List<float>                                             carProgressDistance = new List<float> ();    // know the progression of each car during the race
    29.     public List<int>                                             carLap = new List<int> ();                    // know the number of lap done for each car
    30.     public List<float>                                             carTime = new List<float> ();                // know the time in race for each car
    31.     public List<bool>                                             raceFinished = new List<bool> ();            // Know if the race is finisg-hed for each car
    32.     //public List<int>                                             carPositionAtEnd = new List<int> ();        // Know if a car is on 1 2 3 4 position in a race when race is finished
    33.     public List<int>                                             carPosition = new List<int> ();                // Know if a car is on 1 2 3 4 position in a race
    34.     public float                                                 Timer = 0;                                    // global race timer
    35.     public bool                                                 startTimer = false;                            // know if the timer starts
    36.  
    37.  
    38.     private UnityStandardAssets.Utility.WaypointCircuit         Track;                                         // A reference to the waypoint-based route we should follow
    39.  
    40.     private float                                                trackLengthReference = 0;                    // Save the track length distance.
    41.     public Text                                                 Txt_P1;                                        // Display Player 1 position on race
    42.     public Text                                                 Txt_P2;                                        // Display Player 2 position on race
    43.     public Text                                                 Txt_Timer;                                    // Display global timer
    44.     public Text                                                 Txt_P1_Lap;                                    // Display the number of lap for player 1
    45.     public Text                                                 Txt_P2_Lap;                                    // Display the number of lap for Player 2
    46.     public float                                                RefreshPosTime_ = .2f;
    47.     private float                                                RefreshPositionTimer = 0;
    48.  
    49.     private bool                                                 player2IsManageByCPU = true;                // Know if the player 2 is Manage by the CPU.
    50.     private bool                                                 initDone = false;                            // Know if the Initialialization is done
    51.     public InventoryCar                                         inventoryItemCar;                           // Use to know if LapCOunter is activate for the Race.
    52.  
    53.     private bool b_Multiplayer = false;
    54.     //private int multiplayerNumber = -1;
    55.  
    56. #if PHOTON_UNITY_NETWORKING
    57.     private MCR.GameManager_MCR_Photon gManagerPhoton;
    58. #endif
    59.  
    60.     // --> Initilization
    61.     void Start(){
    62.         if (PlayerPrefs.GetString("Which_GameMode") != "OnlineMultiPlayer")
    63.         {
    64.             StartCoroutine(I_Init());
    65.         }
    66.         else
    67.         {
    68. #if PHOTON_UNITY_NETWORKING
    69.             b_Multiplayer = true;
    70.             gManagerPhoton = GameObject.Find("GM_Photon").GetComponent<MCR.GameManager_MCR_Photon>();
    71.  
    72. #endif
    73.         }
    74.  
    75.     }
    76.  
    77.     private IEnumerator I_Init(){
    78.  
    79.         if (inventoryItemCar)
    80.             b_ActivateLapCounter = inventoryItemCar.b_LapCounter;
    81.  
    82.  
    83.         GameObject tmpObj = GameObject.Find ("Track_Path");
    84.         if (tmpObj) {
    85.             Track = tmpObj.GetComponent<UnityStandardAssets.Utility.WaypointCircuit> ();                    // access the track (car path)
    86.  
    87.         }
    88.  
    89.         tmpObj = GameObject.Find ("Game_Manager");
    90.         if (tmpObj) {
    91.             gameManager = tmpObj.GetComponent<Game_Manager> ();                                             // access the Game_Manager
    92.  
    93.         }
    94.         //Debug.Log("LapStart 1 ");
    95.         yield return new WaitUntil(() => gameManager);
    96.         yield return new WaitUntil(() => gameManager.b_initDone);
    97.  
    98.        // Debug.Log("LapStart 2 ");
    99.         car.Clear();
    100.         carController.Clear();
    101.         carProgressDistance.Clear();
    102.         carLap.Clear();
    103.         carTime.Clear();
    104.         raceFinished.Clear();
    105.         carPosition.Clear();
    106.  
    107.         for (var i = 0; i < gameManager.howManyCarsInRace;i++){
    108.             car.Add(null);
    109.             carController.Add(null);
    110.             carProgressDistance.Add(0);
    111.             carLap.Add(0);
    112.             carTime.Add(0);
    113.             raceFinished.Add(false);
    114.             carPosition.Add(0);
    115.         }
    116.         //Debug.Log("LapStart 3");
    117.         yield return new WaitUntil(() => gameManager.howManyCarsInRace == carPosition.Count);
    118.  
    119.         //if (PlayerPrefs.GetInt ("TestMode") == 1) {                                                           // Init if Test Mode Activated
    120.         //if (gameManager.inventoryItemList.inventoryItem[0].b_TestMode == true) {                                // Init if Test Mode Activated
    121.  
    122.  
    123.  
    124.             InitCar ();
    125.         //}
    126.         //Debug.Log("LapStart 4 ");
    127.         if (car [0] != null && Txt_P1_Lap) {
    128.             Txt_P1_Lap.text = "Lap " + (car [0].iLapCounter).ToString () + "/" + lapNumber.ToString () ;
    129.         }
    130.         if (car [1] != null && Txt_P2_Lap) {
    131.             Txt_P2_Lap.text = "Lap " + (car [1].iLapCounter).ToString () + "/" + lapNumber.ToString ();
    132.         }
    133.  
    134.         yield return null;
    135.     }
    136.  
    137. // --> Init list car and list carController. Call by the Game_Manager or at the beginning of this script if ''Test Mode'' is activated
    138.     public void InitCar(){
    139.         // --> Find car on scene and init Car list carController.
    140.         GameObject[] arrCars = GameObject.FindGameObjectsWithTag ("Car");                          
    141.  
    142.         foreach (GameObject carFind in arrCars) {
    143.             //Debug.Log("car Name: " + carFind.name);
    144.             if (carFind.GetComponent<CarController> ()) {
    145.                 car [carFind.GetComponent<CarController> ().playerNumber - 1] = carFind.GetComponent<CarPathFollow> ();                    // access component for each car
    146.                 carController [carFind.GetComponent<CarController> ().playerNumber - 1] = carFind.GetComponent<CarController> ();        // access component for each car
    147.  
    148.  
    149.                 if (carFind.GetComponent<CarController> ().playerNumber == 2 && carFind.GetComponent<CarAI> ().enabled == false)        // Know if player 2 is manage by a human Player or CPU
    150.                     player2IsManageByCPU = false;
    151.             }
    152.         }
    153.         initDone = true;                                                                                                                // Init done
    154.     }
    155.  
    156. // --> Update function
    157.     void Update(){
    158.         if (!b_Pause && initDone) {
    159.                    
    160.             for (var i = 0; i < car.Count; i++) {
    161.                 if (car [i] != null) {
    162.                     carLap [i] = car [i].iLapCounter;                                                                        // number of lap for each car
    163.                     carProgressDistance [i] = car [i].progressDistance;                                                        // car progression for each car
    164.                 }
    165.             }
    166.             if (Track != null && trackLengthReference == 0)                                                                    // if track
    167.                 trackLengthReference = Track.Length;                                                                        // save the track length
    168.            
    169.             positionOnRace ();                                                                                                // know the position for each car on race
    170.  
    171.             if(startTimer)                                                                                                    // if the race is started
    172.                 F_Timer ();                                                                                                    // Display Timer on screen
    173.         }
    174.  
    175.         /*if (Input.GetKeyDown(KeyCode.G))
    176.         {
    177.             gameManager.RaceIsFinished();
    178.         }*/
    179.     }
    180.  
    181. // --> display timer on screen
    182.     void F_Timer (){
    183.  
    184.         Timer += Time.deltaTime;
    185.         string minutes = "";
    186.         if(Mathf.Floor(Timer / 60) > 0 && Mathf.Floor(Timer / 60) < 10)
    187.             minutes = Mathf.Floor(Timer / 60).ToString("0");
    188.        
    189.         if(Mathf.Floor(Timer / 60) >  10)
    190.             minutes = Mathf.Floor(Timer / 60).ToString("00");
    191.        
    192.         string seconds = Mathf.Floor(Timer % 60).ToString("00");
    193.         string milliseconds = Mathf.Floor((Timer*1000) % 1000).ToString("000");
    194.  
    195.  
    196.         if (Txt_Timer){
    197.             if(Mathf.Floor(Timer / 60) == 0)
    198.                 Txt_Timer.text = seconds + ":" + milliseconds;
    199.             else
    200.                 Txt_Timer.text = minutes + ":" + seconds + ":" + milliseconds;
    201.         }
    202.     }
    203.  
    204.  
    205.  
    206. // --> Display car position on screen
    207.     void positionOnRace (){
    208.         RefreshPositionTimer = Mathf.MoveTowards (RefreshPositionTimer, RefreshPosTime_, Time.deltaTime);
    209.  
    210.  
    211.  
    212.         List<progressionCompare> playersPositions = new List<progressionCompare>();                                // Create a list
    213.  
    214.  
    215.         for(int i = 0; i < car.Count; i++){                                                                        // Create the list with name and scores
    216.  
    217.             float tmpProg = ((carLap [i] * trackLengthReference) + carProgressDistance [i])*1000;
    218.  
    219.             playersPositions.Add (new progressionCompare(car[i], Mathf.RoundToInt(tmpProg)));
    220.         }
    221.  
    222.         playersPositions.Sort();                                                                                // sort the list
    223.         playersPositions.Reverse();                                                                                // reverse list  
    224.  
    225.  
    226.         for(int i = 0; i < playersPositions.Count; i++){                                                        // Create the list with name and scores
    227.             if (b_Multiplayer)
    228.             {
    229.  
    230. #if PHOTON_UNITY_NETWORKING
    231.                 if (raceFinished.Count > 0 && raceFinished[0] == false)
    232.                 {
    233.                  
    234.                     for (var j = 0; j < gManagerPhoton.tmpCarList.Count; j++)
    235.                     {
    236.                         if (gManagerPhoton.tmpCarList[j] && playersPositions[i].car  && gManagerPhoton.tmpCarList[j].gameObject == playersPositions[i].car.gameObject)
    237.                         {
    238.                             int tmpPos = int.Parse(gManagerPhoton.tmpCarList[j].name);
    239.                             tmpPos = carListPUN_MCR.instance.HowManyCarsInCurrentRace - tmpPos +1;
    240.                             if (gManagerPhoton.tmpPhotonManagerList[j] && gManagerPhoton.tmpPhotonManagerList[j].GetComponent<PhotonView>().IsMine)
    241.                             {
    242.                                 if (Txt_P1 && Timer == 0)
    243.                                 {
    244.                                     Txt_P1.text = tmpPos + "/" + carListPUN_MCR.instance.HowManyCarsInCurrentRace;
    245.                                 }
    246.                                 else if (Txt_P1)
    247.                                 {
    248.                                     if (RefreshPositionTimer == RefreshPosTime_)
    249.                                     {
    250.                                         Txt_P1.text = (i + 1) + "/" + carListPUN_MCR.instance.HowManyCarsInCurrentRace;
    251.                                     }
    252.                                     carPosition[0] = i + 1;
    253.                                 }
    254.                             }
    255.                         }
    256.                     }
    257.                 }
    258. #endif
    259.              
    260.                  
    261.  
    262.             }
    263.             else
    264.             {
    265.                 if (raceFinished.Count > 0 && raceFinished[0] == false)
    266.                 {
    267.                     if (playersPositions[i].car == car[0]                                                         // Display on screen Player 1 position
    268.                         && Txt_P1 && Timer == 0)
    269.                     {
    270.                         Txt_P1.text = car.Count + "/" + car.Count;
    271.                     }
    272.                     else if (playersPositions[i].car == car[0] && Txt_P1)
    273.                     {
    274.                         if (RefreshPositionTimer == RefreshPosTime_)
    275.                         {
    276.                             Txt_P1.text = (i + 1) + "/" + car.Count;
    277.                         }
    278.                         carPosition[0] = i + 1;
    279.                     }
    280.                 }
    281.  
    282.                 if (raceFinished.Count > 1 && raceFinished[1] == false)
    283.                 {
    284.                     if (playersPositions[i].car == car[1]                                                         // Display on Screen player 2 position
    285.                        && Txt_P2
    286.                         && Timer == 0)
    287.                     {
    288.                         Txt_P2.text = (car.Count - 1).ToString() + "/" + car.Count;
    289.                     }
    290.                     else if (playersPositions[i].car == car[1] && Txt_P2)
    291.                     {
    292.                         if (RefreshPositionTimer == RefreshPosTime_)
    293.                         {
    294.                             Txt_P2.text = (i + 1) + "/" + car.Count;
    295.                         }
    296.  
    297.                         carPosition[1] = i + 1;
    298.                     }
    299.                 }
    300.  
    301.             }
    302.  
    303.  
    304.  
    305.  
    306.  
    307.             for (var j = 2; j < raceFinished.Count;j++){
    308.                 if (raceFinished.Count > j && raceFinished[j] == false)
    309.                 {
    310.                     if (playersPositions[i].car == car[j])
    311.                         carPosition[j] = i + 1;
    312.                 }
    313.             }
    314.  
    315.         }
    316.         if(RefreshPositionTimer == RefreshPosTime_)
    317.             RefreshPositionTimer = 0;
    318.  
    319.         //-> Prevent a bug if two cars have the same position at the end of the race
    320.         for (int i = 0; i < car.Count; i++)
    321.         {
    322.             for (int j = 0; j < car.Count; j++)
    323.             {
    324.                 if (car[i] != car[j] &&
    325.                     carPosition[i] == carPosition[j] &&
    326.                     raceFinished[i] &&
    327.                     raceFinished[j] ){
    328.                     int whichPositionIsMissing = -1;                         // Position doesn't exist
    329.  
    330.                     //Check if carPosition[i]-1 exist (example 2 if carPosition[i] = 3)
    331.                     for (int k = 0; k < car.Count; k++)
    332.                     {
    333.                         if(carPosition[k] == carPosition[i]-1){            
    334.                             whichPositionIsMissing = carPosition[i] - 1;
    335.                         }  
    336.                     }
    337.  
    338.                     if(whichPositionIsMissing == -1){                       // Position doesn't exist
    339.                         if (carTime[i] < carTime[j])
    340.                             carPosition[i]--;
    341.                         else
    342.                             carPosition[j]--;
    343.                     }
    344.                     else{                                                   // Position exist
    345.                         if (carTime[i] < carTime[j])
    346.                             carPosition[j]++;
    347.                         else
    348.                             carPosition[i]++;
    349.                     }
    350.                 }
    351.             }
    352.         }
    353.  
    354.     }
    355.  
    356. // --> Pause
    357.     public void Pause(){
    358.         if (b_Pause) {                                    // -> Stop Pause
    359.             b_Pause = false;
    360.         }
    361.         else {                                            // -> Start Pause
    362.             b_Pause = true;
    363.         }
    364.     }
    365.  
    366.  
    367.     void OnTriggerEnter(Collider other) {
    368.         CarPathFollow carPathFollow = other.GetComponent<CarPathFollow> ();
    369.         if (other.tag == "Car" && carPathFollow.iLapCounter < lapNumber+1) {                                                    // A car finish a lap
    370.             if(b_ActivateLapCounter){
    371.                 if (b_Multiplayer)
    372.                 {
    373.  
    374. #if PHOTON_UNITY_NETWORKING
    375.  
    376.                         for (var j = 0; j < gManagerPhoton.tmpCarList.Count; j++)
    377.                         {
    378.                             if (gManagerPhoton.tmpCarList[j] && gManagerPhoton.tmpCarList[j].gameObject == other.gameObject)
    379.                             {
    380.                                 if (gManagerPhoton.tmpPhotonManagerList[j].GetComponent<PhotonView>().IsMine)
    381.                                 {
    382.                                     if (carPathFollow.iLapCounter <= lapNumber + 1)
    383.                                     {
    384.                                     Debug.Log("Lap");
    385.                                         Txt_P1_Lap.text = "Lap " + (gManagerPhoton.tmpCarList[j].GetComponent<CarPathFollow>().iLapCounter).ToString() + "/" + lapNumber.ToString();
    386.                                     }
    387.                                 }
    388.                             }
    389.                         }
    390.            
    391. #endif
    392.  
    393.  
    394.  
    395.                 }
    396.                 else
    397.                 {
    398.                     if (carPathFollow.iLapCounter <= lapNumber + 1)
    399.                     {
    400.                         if (car[0] != null && car[0].gameObject == other.gameObject && Txt_P1_Lap)
    401.                         {
    402.                             Txt_P1_Lap.text = "Lap " + (car[0].iLapCounter).ToString() + "/" + lapNumber.ToString();
    403.                         }
    404.                         if (car[1] != null && car[1].name == other.name && Txt_P2_Lap)
    405.                         {
    406.                             Txt_P2_Lap.text = "Lap " + (car[1].iLapCounter).ToString() + "/" + lapNumber.ToString();
    407.                         }
    408.                     }
    409.  
    410.             }
    411.         }
    412.         }
    413.  
    414.         if (b_ActivateLapCounter) {
    415.             if (other.tag == "Car" && carPathFollow.iLapCounter >= lapNumber+1) {                                                // A car finish the race
    416.                 //Debug.Log (other.name + " finished the race");
    417.                 for (var i = 0; i < car.Count; i++) {
    418.                     if (car[i] != null && car[i].gameObject == other.gameObject && raceFinished[i])
    419.                     {
    420.                         carController [i].raceIsFinished = true;      
    421.                     }
    422.  
    423.  
    424.                     if (car [i] != null && car [i].gameObject == other.gameObject && !raceFinished [i]) {
    425.                         raceFinished [i] = true;
    426.                         carTime [i] = Timer;
    427.                         carController [i].raceIsFinished = true;
    428.  
    429.                         //GM_Photon.DisplayScoreMultiOnline(carController[i].gameObject);
    430.  
    431.                         if (PlayerPrefs.GetString("Which_GameMode") == "OnlineMultiPlayer")
    432.                         {
    433.                             #if PHOTON_UNITY_NETWORKING
    434.                             PlayerPrefs.SetInt("CurrentScore", Mathf.RoundToInt(carTime[i] * 1000));
    435.                             MCR.GameManager_MCR_Photon GM_Photon = GameObject.Find("GM_Photon").GetComponent<MCR.GameManager_MCR_Photon>();
    436.  
    437.                             StartCoroutine(GM_Photon.WinProcessOnlineMultiplayer(carController[i].gameObject, Mathf.RoundToInt(carTime[i] * 1000)));
    438.                             #endif
    439.                         }
    440.                         else if (i == 0 && player2IsManageByCPU) {
    441.                             PlayerPrefs.SetInt ("CurrentScore", Mathf.RoundToInt(carTime [i]*1000));
    442.                             gameManager.RaceIsFinished ();
    443.                             CheckIfNextTrackMustBeUnlocked();
    444.                         } else if ((i == 0 || i == 1)  && !player2IsManageByCPU && carController [0] != null && carController [0].raceIsFinished && carController [1] != null  && carController [1].raceIsFinished) {
    445.                             gameManager.RaceIsFinished ();
    446.                             CheckIfNextTrackMustBeUnlocked();
    447.                         }
    448.                     }
    449.                 }
    450.             }
    451.         }
    452.     }
    453.  
    454.     public void displayLap(CarPathFollow carAddLap){
    455.  
    456.     }
    457.  
    458.     void OnDrawGizmos()
    459.     {
    460.  
    461.         Gizmos.color = GizmoColor;                                                                                    // Create a line between the car position and the target position
    462.  
    463.         Matrix4x4 cubeTransform = Matrix4x4.TRS(transform.position, transform.rotation, transform.localScale);
    464.         Gizmos.matrix = cubeTransform;
    465.  
    466.         Gizmos.DrawCube(Vector3.zero, Vector3.one);
    467.         Gizmos.DrawWireCube(Vector3.zero, Vector3.one);
    468.     }
    469.  
    470.  
    471. // --> Compare car position 1st, 2nd, 3, or 4
    472.     public class progressionCompare : IComparable<progressionCompare>
    473.     {
    474.         public CarPathFollow car;
    475.         public int total;
    476.  
    477.         public progressionCompare (CarPathFollow newCar ,int newtotal)
    478.         {
    479.             car = newCar;
    480.             total = newtotal;
    481.         }
    482.  
    483.         //This method is required by the IComparable
    484.         //interface.
    485.         public int CompareTo(progressionCompare other)
    486.         {
    487.             if(other == null)
    488.             {
    489.                 return 1;
    490.             }
    491.  
    492.             //Return the difference in power.
    493.             return total - other.total;
    494.         }
    495.     }
    496.  
    497.     void CheckIfNextTrackMustBeUnlocked()
    498.     {
    499.        /* if (carPosition[0] == 1 && PlayerPrefs.GetString("Which_GameMode") == "Arcade")        // The player 1 win the race and Game Mode = Arcade
    500.         {
    501.             if(SceneManager.GetActiveScene().name == "Track_01_CactusCounty")               // If the current scene is:
    502.             {
    503.                 PlayerPrefs.SetString("Track_02_RockIsland" + "_Lock", "Unlocked");         // Unlock a Scene
    504.             }
    505.         }*/
    506.         //Debug.Log("First: " + carPosition[0]);
    507.     }
    508.  
    509.  
    510.     public void Online_InitLapCOunter()
    511.     {
    512.      
    513.         StartCoroutine(I_Init());
    514.     }
    515. }
    I didn't created this script as I am new in coding and don't know anything about list. This script is included in race game asset, downloaded from unity store.
    I want to know all player positions from another script so that i can compare their positions and adjust AI player car speed according to their position. so for now i just want to know each AI player position from list. please help.
     

    Attached Files:

  2. raarc

    raarc

    Joined:
    Jun 15, 2020
    Posts:
    535
    you never said the name of the list

    but it will be

    Code (CSharp):
    1. public LapCounter lc;
    2.  
    3.  
    drag your script onto the inspector and then

    Code (CSharp):
    1.  
    2. lc. "name of the list you want to acces " [0]
     
    Only4gamers likes this.
  3. Only4gamers

    Only4gamers

    Joined:
    Nov 8, 2019
    Posts:
    327
    I wanted to to check list carPosition values. and i attached a photo also. How your given code will implement in script? please give me an example. I am completely new in coding.
     
  4. raarc

    raarc

    Joined:
    Jun 15, 2020
    Posts:
    535
    like this

    Code (CSharp):
    1.  
    2. public class newscript: MonoBehaviour {
    3.  
    4. public LapCounter lc;
    5.  
    6.  
    7. void Update(){
    8. Debug.Log(lc.carPosition[0]);
    9. }
    10. }
     
    Only4gamers likes this.
  5. Only4gamers

    Only4gamers

    Joined:
    Nov 8, 2019
    Posts:
    327
    Ok. thank you so much for your help. I am checking this now.