- Home /
How to access a variable from another class (GetComponent()?)
Hi.
I am new to Unity and my programming skills are very rusty. Please help me with my Unity3D problem.
I have 2 classes.
public class Ball: MonoBehaviour
()
public class Star: MonoBehaviour
()
Ball playerBall; //is the main player game object in the Unity Hierarchy
Star itemStar; //is a star item game object in the Unity Hierarchy // the playerBall collects stars within the game world.
My question is how can I access a variable from another class.
int starCount;// is a variable inside of the Ball script
I want to access the variable starCount from inside the Star script.
//The following OnTriggerEnter(Collider collision) is located inside the Star script
void OnTriggerEnter(Collider collision)
{
if (collision.gameObject.tag == "ballTriggerCollision")
{
Ball tempBall;
tempBall= this.GetComponent("Ball") as Ball;
tempBall.GetComponent<Ball>().starCount += 1; // ****** THIS IS THE LINE THAT CREATES THE ERROR
killStar();
}
}
The game runs fine until the exact same moment that the Ball Trigger collider collides with the star.
I get an error.
NullReferenceException: Object reference not set to an instance of an object
Ball.OnTriggerEnter (UnityEngine.Collider collision) (at Assets/Scripts/Ball.cs:97)
UnityEditor.Toolbar:OnGUI()
tempBall.GetComponent<Ball>().starCount += 1; // ****** THIS IS THE LINE THAT CREATES THE ERROR
I don't want to add the Ball game object as a variable on the Star script because then I will need to rewrite much of my game code.
If you can help me then I thank you for your help in advance. Your time and energy is appreciated.
massive explanation on unityGE$$anonymous$$S.com
would be pointless to copy it here
Thank you for the resources you have provided. The website http://unityGE$$anonymous$$S.com is greatly helpful. Your time and your help is appreciated!
Answer by FakeBerenger · Nov 07, 2012 at 11:14 PM
The error comes from that line :
tempBall= this.GetComponent("Ball") as Ball;
As you can see, you're getting the component from "this", which is the star. What you want instead, is to get the component from the ball's gameObject. So, do this instead :
tempBall = collision.gameObject.GetComponent<Ball>();
tempBall.starCount += 1; // You could test if tempBall is != null, unless you're sure it won't be.
Thank you for your answer. The Console produces no more errors and the game is increasing the starCount! Your time and your help is appreciated!
Your answer
Follow this Question
Related Questions
can i change a variable from other js? 1 Answer
Passing a Script Name to a Function 2 Answers
Weapon script 0 Answers
Why the variable updates only twice? 1 Answer