how to Add a Certain Amount into a Variable From another Script Unity
Basically I want to Add 30 to my bullets left variable But its in another script and i know how to set it, But not how to add a certain amount to it Please Help Me.
What i was trying to do: using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SingleClip1 : MonoBehaviour {
public AudioClip ClipPickup;
private int AmountToGive = 30;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
void OnTriggerEnter(Collider other)
{
GunScript.bulletsLeft + AmountToGive;
AudioSource.PlayClipAtPoint(ClipPickup, transform.position);
}
}
If i don't have to use a variable that would be nice
Answer by $$anonymous$$ · Feb 21, 2017 at 01:25 AM
Try:
GunScript.bulletsLeft += AmountToGive;
Which is the same thing as:
GunScript.bulletsLeft = GunScript.bulletsLeft + AmountToGive;
This is assuming that the bulletsLeft variable has the static keyword infront of it. If there isn't, you will need to reference a specific GunScript object, and there are many ways to do that.
The way I would go about doing that is finding some way to access the gun script from the collider. There are many ways to go about this, depending on the Hierarchy of your GameObjects. A solution that would work in general (but isn't very efficient and may not work for you) is something like this inside of the OnTriggerEnter method:
other.GetComponentInChildren<GunScript>().bulletsLeft += AmountToGive;
Just make sure there's a public keyword in front of the bulletsLeft variable in any case
Hope this helped!
Your answer
Follow this Question
Related Questions
How to access to a variable in shader from a script ? 1 Answer
Change in Editor via Script Values of another Script 2 Answers
Getting wrong value of variable 1 Answer
How to assign slider to float: Spin, on a gameobject 1 Answer
How would I make a variable equal a variable but only its past value? 1 Answer