0

I want to get mouse position. So I use this code.

My Code Is :

    _targetPos.position = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 10.0f));

enter image description here

enter image description here

enter image description here

As we can see, In this picture R-Value is exist. But Null Reference Exceptioin is occur.

I tried to fix this problem using enter link description here.

I used GameObject.Find(""), but I met same null problem even though R-Value has value.

My main camera object's Tag is like this.

enter image description here

How Can I fix this Null problem?

  • Add : My whole code is this :

public class BulletController : CreatureController {

Transform _targetPos;

protected override void Init() {
    _rigidbody = GetComponent<Rigidbody2D>();
    SetBulletRotation();
}
private void OnEnable() {
    SetBulletRotation();
}

protected override void UpdateIdle() {

}
// [Fixed] Problem : _desPos is not holding
protected override void UpdateMoving() {
    float _bulletSpeed = _speed * 2.0f;
    _rigidbody.MovePosition(transform.position + _destPos * _bulletSpeed * Time.fixedDeltaTime);
    Vector3 bullPos = Camera.main.WorldToViewportPoint(transform.position);
    if (bullPos.x <= -0.05f || bullPos.x >= 1.05f || bullPos.y <= -0.05f || bullPos.y >= 1.05f) {
        Manager.Pool.PushPoolChild(gameObject);
    }
}

protected virtual void SetBulletRotation() {
    //_destPos = shootDir.normalized;
    _targetPos.position = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 10.0f));
    _destPos = (_targetPos.position - transform.position).normalized;
    State = EnumList.CreatureState.Move;
    float angle = Mathf.Atan2(_destPos.y, _destPos.x) * Mathf.Rad2Deg;  
    transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
}
private void OnTriggerEnter2D(Collider2D collision) {
    
    if (collision.gameObject.layer.Equals(6) || collision.gameObject.layer.Equals(8)) {
        return;
    }
    else {
        Manager.Pool.PushPoolChild(gameObject);
    }
    
    
}

}

Namk0207
  • 45
  • 5
  • 3
    It could also be that your `_targetPos` is null. Perhaps checking that would help. – Ibrennan208 Jun 29 '22 at 07:10
  • Posting the rest of your relevant code could help as well. – Ibrennan208 Jun 29 '22 at 07:10
  • Thanks for comment. I just want to get Mouse's Vector3 value. So "_targetPos" is null and try to get Mouse's position. In your comment mean, don't use Transform and use bullet GameObject's transform? – Namk0207 Jun 29 '22 at 07:28

0 Answers0