- Home /
How to access variables from scripts on different objects then display it on a textmesh?
Hello I've been really stumped on how I can display how much ammo a gun has on the text mesh component on the canvas gameObject. I've been searching for solutions all day but I just can't find anything. First I need to access the Ammo variable from a different script and then display that variable on a different component. I have no clue how to get variables from separate scripts on a different object. If anyone could help me with a C# example that would be awesome. My gun script is down below if anyone needs a reference, sorry if it's messy or bad
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Weapon : MonoBehaviour { public float fireRate = 0.5f; //How fast the weapon fires public int Ammo = 3; //How much ammo the weapon fires public float timeToFire = 0.0f; //used for firerate public Transform ejectPoint; //where the bullets are ejected public GameObject bullet; //the bullet object that is spawned public int ReloadAmount = 10; //how much is reloaded at a time // Use this for initialization void Start () { } // Update is called once per frame void Update () { if (fireRate == 0 && Ammo >= 1) { //If it's 0 then it's a semi-auto if (Input.GetButtonDown ("Fire1")) { Instantiate (bullet, ejectPoint.position, ejectPoint.rotation); Ammo = Ammo - 1; } } else if (Input.GetButton ("Fire1") && Time.time >= timeToFire && Ammo >= 1) { //If it's any other positive number then it's auto timeToFire = Time.time + fireRate; Instantiate (bullet, ejectPoint.position, ejectPoint.rotation); Ammo = Ammo - 1; } if (Input.GetButtonDown ("Fire2")) { //Reloading thing Debug.Log ("Reloading..."); Ammo = Ammo + ReloadAmount; } } }
Answer by TheBleedingNova · Oct 07, 2017 at 07:23 AM
Your code isn't indented whatsoever, so it's impossible to read.
To access variables from other scripts you must make an object reference to the script you are trying to access.
Example:
public NameOfYourScript variableName;
NameOfYourScript.VariableOnThatScript = something;
You would assign NameOfYourScript in the inspector on the object that the script is attached to. Then you can access any public variable on that script by using the name of the variable, and then the name of the variable you are trying to access (variable.variableYouAreTryingToAccess).
Your answer
![](https://koobas.hobune.stream/wayback/20220612140447im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
show sync var on two text ui (unet - networking) 3 Answers
Printing text one by one, and changing text colors using Markup 0 Answers
Getting A Variable From a Outside Text File 1 Answer
Text popup on target hit 2 Answers
How do I bring variables from two scripts to one then have them print on a canvas text? 0 Answers