Search Unity

Accessing another scripts variables with another script

Discussion in '2D' started by Deanford, Aug 16, 2017.

  1. Deanford

    Deanford

    Joined:
    Oct 17, 2014
    Posts:
    93
    Hi,

    I want to change the variable in the picture below using another script... does anyone know how to achieve that? Help would be greatly appreciated!

    http://imgur.com/a/ctikr

    Dean
     
  2. Deleted User

    Deleted User

    Guest

    You would want to make sure the variable is set to public, you would then access that gameobject from your script however you chose to do so and someobject.getcomponent<Inventory_2>().yourvariable
     
  3. Deanford

    Deanford

    Joined:
    Oct 17, 2014
    Posts:
    93
    Thanks for the reply, however I can only access the Items variable and cant seem to access the "COPPER"'s count variable http://imgur.com/a/qKbTG
     
  4. Reloque

    Reloque

    Joined:
    Apr 28, 2015
    Posts:
    207
    Give one script a reference to the other. Then either set a public variable, not the best solution however, or use a Getter/Setter type construction.

    Something like this;

    Code (csharp):
    1.  
    2. // Public GameObject to be set
    3. public CopperCounterScript copperCounter;
    4.  
    5. void OnCopperCounterUpdate()
    6. {
    7.   copperCounter.count = 12;
    8. }
    9.  
    Of course, you need to set copperCounter in either the inspector, or runtime in code.
     
  5. Deleted User

    Deleted User

    Guest

    in that case your variable name would be items[3].count since the name of the list is items and the position of the copper object is 4th (0123) then you can access the count
     
  6. Deanford

    Deanford

    Joined:
    Oct 17, 2014
    Posts:
    93
    Thanks for the reply, could I get an example if possible please?
     
  7. Deleted User

    Deleted User

    Guest

    Your inventory script would be something like
    Code (csharp):
    1.  
    2. public class test_script : MonoBehaviour
    3. {
    4.  
    5.     [Serializable] public class Item
    6.     {
    7.         public string name;
    8.         public int count;
    9.     }
    10.  
    11.     public List<Item> items;
    12. }
    13.  
    and you would access it with something like this
    Code (csharp):
    1.  
    2. public class test_script_2 : MonoBehaviour {
    3.  
    4.     [SerializeField]
    5.     private GameObject otherObject;
    6.  
    7.     void Start () {
    8.         otherObject.GetComponent<test_script>().items[1].count = 3;
    9.     }
    10. }
    11.  
     
  8. Deanford

    Deanford

    Joined:
    Oct 17, 2014
    Posts:
    93
    Thanks for the reply man!

    I think im getting myself confused with this lol, to make it easier, here is the script below, I have made a function called SalvageShuttle which is when I add 10 to the copper count and inventory text.

    How would I implement it with the code below?

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

    public class inventory_2 : MonoBehaviour {

    // a class of data representing one item
    [System.Serializable] public class Item {
    public string name;
    public GameObject prefab;
    public Sprite previewSprite;
    public int Count;
    }

    public List<Item> items; // setup in the inspector

    // component references
    public Text InventoryText;
    public Text selectionText;
    public Image previewImage;

    Item selectedItem;
    int selectedIndex;

    void Start()
    {
    InventoryText = GameObject.Find("inventory_text").GetComponent<Text>();
    selectionText = GameObject.Find("selected_block_text").GetComponent<Text>();
    previewImage = GameObject.Find("selected_item").GetComponent<Image>();
    }

    void Update()
    {
    if (selectedIndex < 0)
    {
    selectedIndex = items.Count - 1;
    }

    if (selectedIndex > items.Count - 1) {
    selectedIndex = 0;
    }

    if (Input.GetAxis("Mouse ScrollWheel") > 0) //Scroll up
    {
    selectedIndex++;
    }

    if (Input.GetAxis("Mouse ScrollWheel") < 0) //Scroll up
    {
    selectedIndex--;
    }

    //Place blocks
    if (Input.GetMouseButtonDown(1))
    {
    if (items[selectedIndex].Count > 0)
    {
    Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);

    Vector3 placePos = new Vector3(Mathf.Round(mousePos.x), Mathf.Round(mousePos.y), 0f);

    if (Physics2D.OverlapCircleAll(placePos, 0.25f).Length == 0)
    {
    GameObject newTile = Instantiate(items[selectedIndex].prefab, placePos, Quaternion.identity) as GameObject;
    items[selectedIndex].Count--;
    }
    }
    }

    //When C is pressed, converts 2 sand into 1 glass block
    if (selectedIndex == 0)
    {
    if (Input.GetKeyDown(KeyCode.C))
    {
    if (items[7].Count >= 2)
    {
    Add(6, 1);
    Add(7, -2);
    }
    }
    }

    SetSelectedItem(items[selectedIndex]);
    }

    public void Add(int tileType, int count)
    {
    items[tileType].Count += count;
    }

    private void SetSelectedItem(Item newSelection)
    {
    if (selectedItem != newSelection)
    {
    selectedItem = newSelection;

    previewImage.sprite = selectedItem.previewSprite;

    UpdateInventoryText();
    }
    }

    private void UpdateInventoryText()
    {
    // make an array of all the item names
    string[] itemNames = new string[items.Count];

    for (int i = 0; i < itemNames.Length; i++)
    {
    Item item = items;
    // format the display string
    itemNames = string.Format("{0}: {1}", item.name, item.Count);
    }

    // join the array with new lines
    InventoryText.text = string.Join("\n", itemNames);
    }

    public void SalvageShuttle()
    {
    if (Input.GetMouseButtonDown(0))
    {
    if (gameObject.tag == "shuttle")
    {
    // ADD 10 TO THE INVENTORY TEXT AND COPPER COUNT HERE <-------------
    }
    }
    }
    }
    Code (CSharp):
    1. using System;
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using UnityEngine;
    5. using UnityEngine.UI;
    6.  
    7. public class inventory_2 : MonoBehaviour {
    8.  
    9.     // a class of data representing one item
    10.     [System.Serializable] public class Item {
    11.         public string name;
    12.         public GameObject prefab;
    13.         public Sprite previewSprite;
    14.         public int Count;
    15.     }
    16.  
    17.     public List<Item> items; // setup in the inspector
    18.  
    19.     // component references
    20.     public Text InventoryText;
    21.     public Text selectionText;
    22.     public Image previewImage;
    23.  
    24.     Item selectedItem;
    25.     int selectedIndex;
    26.  
    27.     void Start()
    28.     {
    29.         InventoryText = GameObject.Find("inventory_text").GetComponent<Text>();
    30.         selectionText = GameObject.Find("selected_block_text").GetComponent<Text>();
    31.         previewImage = GameObject.Find("selected_item").GetComponent<Image>();
    32.     }
    33.  
    34.     void Update()
    35.     {
    36.         if (selectedIndex < 0)
    37.         {
    38.             selectedIndex = items.Count - 1;
    39.         }
    40.  
    41.         if (selectedIndex > items.Count - 1) {
    42.             selectedIndex = 0;
    43.         }
    44.  
    45.         if (Input.GetAxis("Mouse ScrollWheel") > 0) //Scroll up
    46.         {
    47.             selectedIndex++;
    48.         }
    49.  
    50.         if (Input.GetAxis("Mouse ScrollWheel") < 0) //Scroll up
    51.         {
    52.             selectedIndex--;
    53.         }
    54.  
    55.         //Place blocks
    56.         if (Input.GetMouseButtonDown(1))
    57.         {
    58.             if (items[selectedIndex].Count > 0)
    59.             {
    60.                 Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    61.  
    62.                 Vector3 placePos = new Vector3(Mathf.Round(mousePos.x), Mathf.Round(mousePos.y), 0f);
    63.  
    64.                 if (Physics2D.OverlapCircleAll(placePos, 0.25f).Length == 0)
    65.                 {
    66.                     GameObject newTile = Instantiate(items[selectedIndex].prefab, placePos, Quaternion.identity) as GameObject;
    67.                     items[selectedIndex].Count--;
    68.                 }
    69.             }
    70.         }
    71.  
    72.         //When C is pressed, converts 2 sand into 1 glass block
    73.         if (selectedIndex == 0)
    74.         {
    75.             if (Input.GetKeyDown(KeyCode.C))
    76.             {
    77.                 if (items[7].Count >= 2)
    78.                 {
    79.                     Add(6, 1);
    80.                     Add(7, -2);
    81.                 }
    82.             }
    83.         }
    84.  
    85.         SetSelectedItem(items[selectedIndex]);
    86.     }
    87.  
    88.     public void Add(int tileType, int count)
    89.     {
    90.         items[tileType].Count += count;
    91.     }
    92.  
    93.     private void SetSelectedItem(Item newSelection)
    94.     {
    95.         if (selectedItem != newSelection)
    96.         {
    97.             selectedItem = newSelection;
    98.  
    99.             previewImage.sprite = selectedItem.previewSprite;
    100.  
    101.             UpdateInventoryText();
    102.         }
    103.     }
    104.  
    105.     private void UpdateInventoryText()
    106.     {
    107.         // make an array of all the item names
    108.         string[] itemNames = new string[items.Count];
    109.  
    110.         for (int i = 0; i < itemNames.Length; i++)
    111.         {
    112.             Item item = items[i];
    113.             // format the display string
    114.             itemNames[i] = string.Format("{0}: {1}", item.name, item.Count);
    115.         }
    116.  
    117.         // join the array with new lines
    118.         InventoryText.text = string.Join("\n", itemNames);
    119.     }
    120.  
    121.     public void SalvageShuttle()
    122.     {
    123.         if (Input.GetMouseButtonDown(0))
    124.         {
    125.             if (gameObject.tag == "shuttle")
    126.             {
    127.                 // ADD 10 TO THE INVENTORY TEXT AND COPPER COUNT HERE <-------------
    128.             }
    129.         }
    130.     }
    131. }
    132.  
    133.  
     
  9. Deleted User

    Deleted User

    Guest

    Your function SalvageShuttle() will need to be called every frame in order to get the mouse down event, when you say if(gameObject.tag == "shuttle") you're referencing the gameobject that this script is attached to not the one you clicked on. If you want to find out which game object you clicked on and react based on its tag you could put something like this in your update function:
    Code (csharp):
    1.  
    2.         if (Input.GetMouseButtonDown(0))
    3.         {
    4.             var other = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero);
    5.             if (other.collider.tag == "shuttle")
    6.             {
    7.                 var copper = items.Find(item => item.name.Contains("copper"));
    8.                 copper.count += 10;
    9.             }
    10.  
    11.         }
    12.  
     
    Deanford likes this.
  10. Deanford

    Deanford

    Joined:
    Oct 17, 2014
    Posts:
    93
    I see, instead of putting it in the Update I have kept it in its own function but I am calling the function in update now. However, I used the code above and I get an red line under "count" here:

    Code (CSharp):
    1. copper.count += 10;
    it says the script does not contain a definition for count etc.
     
  11. Deleted User

    Deleted User

    Guest

    yours is Count actually
     
    Deanford likes this.
  12. Deanford

    Deanford

    Joined:
    Oct 17, 2014
    Posts:
    93
    Thanks man! Got it to work now with your help! Much appreciated!
     
    Deleted User likes this.