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));
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.
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);
}
}
}