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().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().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.