I'm making a 2D game, and I want to change a variable's value when I click one of my sprites. How should I do that??
It's a game and you click a game object to control it. I definitely can't just make it into a UI element. What's the best way to detect a click on a game object???
What I ended up doing was making a game object that would have a collision and would act as a trigger. This game object followed the mouse, and was tagged, "mouse". It used this code:
w = Screen.width;
h = Screen.height;
mouseFollow.gameObject.transform.position = new Vector2 ((-w/2f + Input.mousePosition.x)*18/w, (-h/2f + Input.mousePosition.y)*10/h);
Once I had that, I basically said, I checked for a trigger and mouse click:
void OnTriggerStay2D (UnityEngine.Collider2D newCollision) {
if (newCollision.gameObject.tag == "mouse") {
if (Input.Get$$anonymous$$ouseButtonDown (0)) {
active = true;
}
}
}
On click, it would change the bool active to true. I don't know if this was the best way, but it's what I thought of. Any more input would be greatly appreciated.
Answer by ArturoSR · Jul 20, 2016 at 11:04 PM
The best way to detect a mouse pick is using the Physics.RayCast(), obviously you need to have a Game Object with a collider (no matter what type) and a rigid body this two components attached to it (for your safety turn the Is Kinematic on), for more reference check the documentation, cheers.
Answer by Anas173 · Jul 20, 2016 at 09:31 PM
I dont really understand your question but i guess you want something that works with mouse..
So.. Try OnMouseDown() Function
Your answer
Follow this Question
Related Questions
ScreenPointToRay 0 Answers
2D player enter/exit orbit 0 Answers
Help! Create interactive button with an image + c# Script 0 Answers
Player Respawn Problem, Bullets dont move! [C#] 0 Answers
Unity 2D - Material for light 2 Answers