How to access a variable from another script in another gameobject through GetComponent?

Solution 1:

You need to find the GameObject that contains the script Component that you plan to get a reference to. Make sure the GameObject is already in the scene, or Find will return null.

 GameObject g = GameObject.Find("GameObject Name");

Then you can grab the script:

 BombDrop bScript = g.GetComponent<BombDrop>();

Then you can access the variables and functions of the Script.

 bScript.foo();

I just realized that I answered a very similar question the other day, check here: Don't know how to get enemy's health


I'll expand a bit on your question since I already answered it.

What your code is doing is saying "Look within my GameObject for a BombDropScript, most of the time the script won't be attached to the same GameObject.

Also use a setter and getter for maxBombs.

public class BombDrop : MonoBehaviour
{
    public void setMaxBombs(int amount)
    {
        maxBombs += amount;
    }

    public int getMaxBombs()
    {
        return maxBombs;
    }
}

Solution 2:

use it in start instead of awake and dont use Destroy(gameObject); you are destroying your game Object then you want something from it

void Start () {
     BombDropScript =gameObject.GetComponent<BombDrop> ();
     collider = gameObject.GetComponent<BoxCollider2D> ();

     // Call the Explode function after a few seconds
     Invoke("Explode", time);

 }

void Explode() {
//..
  //..
//at last
Destroy(gameObject);
 }

if you want to access a script in another gameObject you should assign the game object via inspector and access it like that

 public gameObject another;
void Start () {
     BombDropScript =another.GetComponent<BombDrop> ();
}