In my 3d game on a unit, I click on objects, after which some action takes place. For this, I determine that the player is looking at the object, that he is close enough, and that he pressed the LMB. But if the first press takes place without errors, then to interact with the object it is enough to look at it, you do not need to press the LMB - I want to fix it.
private Collider thisCollider; // ΠΊΠΎΠ»Π»Π°ΠΉΠ΄Π΅Ρ ΠΎΠ±ΡΠ΅ΠΊΡΠ°, Π½Π° ΠΊΠΎΡΠΎΡΡΠΉ Π½Π°ΠΆΠΈΠΌΠ°Π΅ΠΌ public int ActionNumber { get; private set; } void Start () { thisCollider = GetComponent<Collider>(); } void Update () { if (Input.GetButton("Fire1") && DoPlayerLookAtObject()) ActionsList(); } bool DoPlayerLookAtObject() { int layerMask = 1 << 9; // ΠΈΠ³Π½ΠΎΡΠΈΡΡΡ ΠΊΠΎΠ»Π»Π°ΠΉΠ΄Π΅Ρ ΠΈΠ³ΡΠΎΠΊΠ° layerMask = ~layerMask; RaycastHit _hit; Ray _ray = Camera.main.ScreenPointToRay(new Vector3(Screen.width / 2, Screen.height / 2, 0)); bool isHit = Physics.Raycast(_ray, out _hit, 2.0f, layerMask); if (isHit && _hit.collider == thisCollider) return true; // Π·Π΄Π΅ΡΡ ΠΎΡΠΈΠ±ΠΊΠ° - Π²ΡΠ΅ Π²ΡΠ΅ΠΌΡ Π²ΠΎΠ·Π²ΡΠ°ΡΠ°Π΅Ρ true ΠΏΠΎΡΠ»Π΅ ΠΏΠ΅ΡΠ²ΠΎΠ³ΠΎ Π½Π°ΠΆΠ°ΡΠΈΡ Π½Π° ΠΎΠ±ΡΠ΅ΠΊΡ else return false; } public bool ActionsList() { if (DoPlayerLookAtObject()) switch (thisCollider.name) { // Ρ ΠΊΠ°ΠΆΠ΄ΠΎΠ³ΠΎ ΠΎΠ±ΡΠ΅ΠΊΡΠ°, Ρ ΠΊΠΎΡΠΎΡΡΠΌ Π²Π·Π°ΠΈΠΌΠΎΠ΄Π΅ΠΉΡΡΠ²ΡΡ, Π΅ΡΡΡ ΠΊΠΎΠ»Π»Π°ΠΉΠ΄Π΅Ρ, // ΡΠ½ΠΈΠΊΠ°Π»ΡΠ½ΠΎΠ΅ ΠΈΠΌΡ ΠΈ ΠΏΡΠΈΠΊΡΠ΅ΠΏΠ»Π΅Π½Π½ΡΠΉ Π΄Π°Π½Π½ΡΠΉ ΠΊΠ»Π°ΡΡ case "barthender": ActionNumber = 1; return true; case "doorToStreet": ActionNumber = 2; return true; default: Debug.Log("Error: Out of range"); break; } return false; } For each object with which there will be an interaction, I attach the top script, and in another class I check if there was a click:
// Π΄Π»Ρ ΠΊΠ°ΠΆΠ΄ΠΎΠ³ΠΎ ΠΎΠ±ΡΠ΅ΠΊΡΠ°, Π½Π° ΠΊΠΎΡΠΎΡΡΠΉ Π±ΡΠ΄Π΅ΠΌ Π½Π°ΠΆΠΈΠΌΠ°ΡΡ, ΡΠ²ΠΎΡ ΠΏΠ΅ΡΠ΅ΠΌΠ΅Π½Π½Π°Ρ public OnMousePressCasino onMousePressCasinoBarthender; public OnMousePressCasino onMousePressCasinoDoorToStreet; // ΠΏΠΎ Π½ΠΎΠΌΠ΅ΡΡ ΠΎΠΏΡΠ΅Π΄Π΅Π»ΡΠ΅ΠΌ, Π½Π° ΠΊΠ°ΠΊΠΎΠΉ ΠΎΠ±ΡΠ΅ΠΊΡ ΠΎΠΆΠΈΠ΄Π°Π΅ΡΡΡ Π½Π°ΠΆΠ°ΡΠΈΠ΅ if (onMousePressCasinoBarthender.ActionNumber == 1 && onMousePressCasinoBarthender.ActionsList()) // do something if (onMousePressCasinoDoorToStreet.ActionNumber == 2 && onMousePressCasinoDoorToStreet.ActionsList()) // do something
if (onMousePressCasinoBarthender.ActionNumber == 1 && onMousePressCasinoBarthender.ActionsList())- Dima Kozyr