How to access gameObject variable script

I have 3 GameObjects in my screen.
if i hit a particular gameObject i need to access his variable and change the variable(count), which started with zero, to 1, then 2, then 3 … etc.

How can i access this variable to make changes?
Some hint in C#?

Use GameObject.GetComponent to return the script, and then set its variable count to whatever you want. For example:

Counter counter = GameObject.Find(“Your GameObject”).GetComponent();
counter.count++;

You will have to add using System.Collections.Generic for the above to work.

You can do it two ways:

Either the script does it on it’s own on every object using OnMouseEnter, OnMouseExit and OnMouseButtonDown

bool mouseIsOverObject = false;
bool thisObjectsCounter = 0;

void OnMouseEnter()
{
   mouseIsOverObject = true;
}

void OnMouseExit()
{
   mouseIsOverObject = false;
}

void Update()
{
   if(Input.GetMouseButtonDown(0)&&mouseIsOverObject )
       thisObjectsCounter++;
}

or

You have a script on your camera that uses raycast, raycasthit to get the hit object; your 3 objects than need colliders though.
That way you get the hit object, then you can access it’s script with GetComponent and then add one to your particular variable.

Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

RaycastHit hit;
if (Physics.Raycast(ray, out hit, 100))
{
   if(hit!=null)
      hit.collider.gameObject.GetComponent<MyScriptClass>().thisObjectsCounter++;
}