- Home /
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 :)
they are not in same object
You are trying to access the component "shipupgrade" on your sphere gameobject, but not your cube gameobject.
You have to access the cubes gameobject by either linking it in the editor into your script, finding it with findGameObject.
var myCube : GameObject
// Dostuff
if(myCube.GetComponent(shipupgrade).shipupgrade == 1) {
}
// Do more stuff
or you can also to find your cube by using
GameObject.Find("cubeName").GetComponent(shipupgrade).shipupgrade == 1
// or
GameObject.FindGameobjectWithTag("cubeTag")GetComponent(shipupgrade).shipupgrade == 1
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
}
}
}
Answer by meat5000 · Nov 23, 2013 at 12:20 PM
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);
}
}
Your answer
Follow this Question
Related Questions
How do you make a trig object? 0 Answers
Why sound doesn't stop? 2 Answers
First time open error android game 0 Answers
User input display 1 Answer
Random numbers please help 1 Answer