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 
  • one
    docs.unity3d.com/ScriptReference/ ... It works when pressed. Your code is too complicated to handle. Or even so docs.unity3d.com/ScriptReference/MonoBehaviour.OnMouseDown.html - Valera Kvip
  • You do not see where the treatment of pressing. - Valera Kvip
  • @ValeraKvip Here if (onMousePressCasinoBarthender.ActionNumber == 1 && onMousePressCasinoBarthender.ActionsList()) - Dima Kozyr
  • It's clear. Where is it called? What function? - Valera Kvip
  • one
    I mean, there is no click test. Therefore, it will always be executed on hover. Remove it from the update and put it in one of the functions to which I gave links above. - Valera Kvip

0