- Home /
 
               Question by 
               Kagraxx · May 04, 2015 at 06:13 AM · 
                physicsrigidbody2dvelocitynullreferenceexceptionmovment  
              
 
              NullReferenceException: UnityEngine.Rigidbody2D.get_velocity()
I get this null exception every time i try to move my character, I am trying to move my character using 2 different methods. I am new to Unity coming from Monogame and XNA. Here is my code:
 private Rigidbody2D _rig;
 void Start(){
     _rig = GetComponent<Rigidbody2D>();
 void Update(){
     _position.x = Input.GetAxis ("Horizontal");
     _position.y = Input.GetAxis ("Vertical");
 }
 
 void FixedUpdate () {
     if (Input.GetKeyDown(KeyCode.Space))
     {    
         _rig.AddForce(new Vector2(_rig.velocity.x, _jumpHeight));
         _rig.velocity = new Vector2(Mathf.Clamp(_rig.velocity.x, -_clampValue.x, _clampValue.x), Mathf.Clamp(_rig.velocity.y, -_clampValue.y, _clampValue.y));
     }
     if (Input.GetKey(KeyCode.D))
     {
         //_rig.AddForce(new Vector2(_moveSpeed, _rig.velocity.x));
         //_rig.velocity = new Vector2(Mathf.Clamp(_rig.velocity.x, -_clampValue.x, _clampValue.x), Mathf.Clamp(_rig.velocity.y, -_clampValue.y, _clampValue.y));
         _rig.velocity = new Vector2(_position.x * _moveSpeed, _rig.velocity.y);
     }
     if (Input.GetKey(KeyCode.A))
     {
         _rig.AddForce(new Vector2(-_moveSpeed, _rig.velocity.y));
         _rig.velocity = new Vector2(Mathf.Clamp(_rig.velocity.x, -_clampValue.x, _clampValue.x), Mathf.Clamp(_rig.velocity.y, -_clampValue.y, _clampValue.y));
     }
 }
               Comment
              
 
               
              Do you have Rigidbody2D on object which contains this script? Do you assign its Rigidbody2D to your _rig variable? If you have and you do then show how you do that.
I believe you just forgot closing bracket in Start function while you were posting here and you have defined all your variables. I believe as well that you've rechecked from my previous comment that you have Rigidbody2D, though just in case you can verify that:
 private Rigidbody2D _rig;
 void Start()
 {
     _rig = GetComponent<Rigidbody2D>();
     Debug.Log(_rig != null);
 }
But what I'd really want you to do now - post the actual error along with pointing out to which line of code here it refer.
Your answer
 
 
              koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                