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

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;
    }
}

Leave a Comment