0
\$\begingroup\$

Why does the following code not working? (weird, sometimes it works sometimes not )

I want to move player by touching on the screen and change the color of gameObject when detect trigger and release mouse click.

"Drag and move" script works correctly I just add following code and sometimes it works sometimes not

  private void OnTriggerStay2D(Collider2D colider)
  {
    
    if (Input.GetMouseButtonUp(0) & colider != null)
    {
      colider.gameObject.GetComponent<SpriteRenderer>().material.color = Color.blue;

    }

  }

There is a full script :

  private Camera _cam;
  private Vector3 _daragOfset;
  [SerializeField] private float _speed = 4.55f;
  private bool isEntered = false;

  void Update()
  {
    if (Input.GetMouseButtonDown(0))
    {
      _daragOfset = transform.position - GetMousePos();
    }
  }

  private void OnTriggerStay2D(Collider2D colider)
  {
    if (Input.GetMouseButtonUp(0) & colider != null)
    {
      colider.gameObject.GetComponent<SpriteRenderer>().material.color = Color.blue;
    }
  }

  void Awake()
  {
    _cam = Camera.main;
  }

  void OnMouseDrag()
  {
    transform.position = Vector3.MoveTowards(transform.position, GetMousePos() + _daragOfset,_speed * Time.deltaTime);
  }

  Vector3 GetMousePos()
  {
    var mousePos = _cam.ScreenToWorldPoint(Input.mousePosition);
    mousePos.z = 0;
    return mousePos;
  }

enter image description here

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

Note that you have used only one & in the if statement, what you really wanted was the AND Operator (&&). Here is the edited code:

if (Input.GetMouseButtonUp(0) && colider != null)
{
  colider.gameObject.GetComponent<SpriteRenderer>().material.color = Color.blue;
}
\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .