- Home /
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#?
Answer by cmpgk1024 · Aug 11, 2013 at 09:38 PM
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.
And if i have the same script attached to the 3 gameObjects?
Never$$anonymous$$d figured this out ... just counter = hit.collider.gameObject.GetComponent();
Answer by Joyrider · Aug 11, 2013 at 09:38 PM
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++;
}
Your answer
Follow this Question
Related Questions
Change and Access another scripts Variables 1 Answer
Refering to gameobject script is attached to 1 Answer
My marble (Player/Gameobject) goes through the "play board" (gameobject). Why? 1 Answer
Accessing a variable effected by a GUI slider from another scipt 1 Answer
Is it possible to change a variable, into a script not assigned to any game object? 3 Answers