accessing a variable from one script and object in another with Unity

I have two scripts ;

My first script is shipupgrade in the first object Cube;

var shipupgrade : int = 1;
 
function Start () {
 
}
 
function Update () {
 
}

and here is my second script script name : destroy in the second object Sphere;

function Start () {}
 
function Update () {
  if(Input.GetKeyDown("u")) 
    if(gameObject.GetComponent(shipupgrade).shipupgrade == 1) {
    gameObject.GetComponent(shipupgrade).shipupgrade += 1;
    Destroy(this.gameObject);
  }
}

this doesnt work why ? help me please it says Object reference not set to an istance of an object so what i must write ? thanks :slight_smile:

they are not in same object

If you intend to sail into this object, you may want to look into the monobehaviour reference and look for OnCollisionEnter(Collision) OnCollisionEnter( Collision target ) { if(target.gameObject.tag == "cubeTag") { if(target.gameObject.GetComponent(shipupgrade).shipupgrade == 1 ) { // Dostuff } } }

1 Answer

1

Something like this will work. In your script you need to reference the Gameobject you are trying to get the script and variable from.

var cubeInstance : GameObject;

function Start () {cubeInstance  = GameObject.Find("Cube")}

function Update () {
     if(Input.GetKeyDown("u"))
     if(cubeInstance.gameObject.GetComponent(shipupgrade).shipupgrade == 1) {
     cubeInstance.gameObject.GetComponent(shipupgrade).shipupgrade += 1;
     Destroy(this.gameObject);
     }
}