GetComponent() access a variable from another class

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.

There are tons of ways to do this, try to use SendMessage().

Try something like this:

void OnTriggerEnter(Collider collision)
{
    if (collision.gameObject.tag == "ballTriggerCollision")
    {
        Ball tempBall = collision.gameObject.GetComponent<Ball>(); 
        tempBall.starCount += 1; // ****** THIS IS THE LINE THAT CREATES THE ERROR 

        killStar();
    }
}

The star is probably running into a game object that is not a Ball, yet have the tag ballTriggerCollision. You have a NullReferenceException, it means that a variable do not point to something ; therefore it points to null. tempBall is probably null, so you must add a security, so nothing happens when the star touches something else that the ball.

if (tempBall != null)
{
tempBall.starCount += 1;
killStar ();
}

instead of this:

tempBall.GetComponent().starCount += 1;

write this:

tempBall.starCount += 1;

Thanks for the advice!