- Home /
Clicking on a Cube. Then -1 a varible
I'm kind of new to Unity3d scripting. And I want to when I click on a Cube that a variable will decrease. Example: wood -= 1
I have set the cubes tag as: Player
So how do I do it? I don't know. I have tried several things. Like Raycast. But I'm not sure if that is used for that. So what do I do?
[EDIT] The script with the "wood" variable is attached to the camera. And I need to decrease the wood variable by clicking on the cube.
Answer by creighcl · Jul 15, 2013 at 08:18 PM
you need to make sure the "wood" variable is accessible by other scripts. Either its a public variable or you have a public 'setter' method in that script.
Use a raycast to find what was clicked on. If it has the "player" tag, let's subtract the wood from that variable using whatever method you are using. (Script untested, but should get you started)
If (Input.getMouseButtonUp(0)){
RaycastHit hit;
Ray ray = camera.ScreenPointToRay(Input.MousePosition);
if (Physics.Raycast(ray, out hit, 100.0f))
{
//Here's the first object the ray found
Collider clicked = hit.collider;
if (clicked.gameObject.tag == "Player"){
//call your method to subtract wood
camera.getComponent<Stats>().wood--; //or whatever
}
}
}
Don't Work. I'm using JavaScript. Is that the reason? It doesn't like:
RaycastHit hit;
Ray ray = camera.ScreenPointToRay(Input.$$anonymous$$ousePosition);
Collider clicked = hit.collider;
I don't know much about JS, but I think it's hit : RaycastHit, and clicked : Collider
Your answer
Follow this Question
Related Questions
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
Assigning varaibles to prefabs 1 Answer
Tagging Trees placed by tree paint 1 Answer
Acces to a var from another Script. 2 Answers