- Home /
Accessing variables from another object?
i have been reading the scripting reference and looking for answers... (accessing game objects and game components) here is my scenario can somebody help me? i am not really good with programming but i am trying!
i have this 2 objects cube which has box.js and a sphere which has a ball.js attached on it...
ball.js contains the following health = 100;
function disp() { print(health); }
and box js has a onmousedown event which is to retrieve the value of health from the ball when i click it... here is my code on box.js
function OnMouseDown () { var otherScript: ball = GetComponent(ball); otherScript.disp(); }
however when i go run and click the cube it says object reference not set to an object help pls if possible kindly put in comments so i can understand the functionality
Answer by whydoidoit · Sep 15, 2012 at 02:27 PM
The GetComponent called in OnMouseDown is looking for the ball script on the box. You need to have something that is referencing the ball in order to get that script.
In the box you could have a variable that you set to the ball using the Inspector - then you can call GetComponent on that variable (or just make the variable of type ball and you won't need to).
Your answer
Follow this Question
Related Questions
Check if Object is of Type Component 2 Answers
Accesing components on multiple objects in scene 3 Answers
Slider restrictions 0 Answers
Get a GameObject from a component 1 Answer
Interact with Objects with scripts 2 Answers