Accessing another scripts variables with another script

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!

Imgur

Dean

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

Thanks for the reply, however I can only access the Items variable and cant seem to access the “COPPER”'s count variable Imgur: The magic of the Internet

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;

// Public GameObject to be set
public CopperCounterScript copperCounter;

void OnCopperCounterUpdate()
{
  copperCounter.count = 12;
}

Of course, you need to set copperCounter in either the inspector, or runtime in code.

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

Thanks for the reply, could I get an example if possible please?

Your inventory script would be something like

public class test_script : MonoBehaviour
{
  
    [Serializable] public class Item
    {
        public string name;
        public int count;
    }

    public List<Item> items;
}

and you would access it with something like this

public class test_script_2 : MonoBehaviour {

    [SerializeField]
    private GameObject otherObject;

    void Start () {
        otherObject.GetComponent<test_script>().items[1].count = 3;
    }
}

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 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();
selectionText = GameObject.Find(“selected_block_text”).GetComponent();
previewImage = GameObject.Find(“selected_item”).GetComponent();
}

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 <-------------
}
}
}
}
```csharp
*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[i];
        // format the display string
        itemNames[i] = 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 <-------------
        }
    }
}

}
_
```*_

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:

        if (Input.GetMouseButtonDown(0))
        {
            var other = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero);
            if (other.collider.tag == "shuttle")
            {
                var copper = items.Find(item => item.name.Contains("copper"));
                copper.count += 10;
            }

        }
1 Like

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:

copper.count += 10;

it says the script does not contain a definition for count etc.

yours is Count actually

1 Like

Thanks man! Got it to work now with your help! Much appreciated!

1 Like