NullReferenceException

NullReferenceException

本文介绍了我如何修复NullReferenceException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到一个NullReferenceException:对象引用没有设置为对象的瞬间。



我是初学者,并通过视频学到了这一点。所有代码都很好,但空行显示:



playerRigidBody.MovePosition(transform.position + movement);



我已经尝试了几个小时来编写代码,但没有将其钉住。我需要帮助。





I am getting a NullReferenceException: object reference not set to an instant of an object.

I am a beginner and had learned this through a video. All the code is good but the null appears on the line:

"playerRigidBody.MovePosition(transform.position + movement);"

I have tried for several hours to write the code but have not nailed it. I do need help.


using UnityEngine;
using System.Collections;

public class CharacterMovement : MonoBehaviour 

{
public float speed = 6f;		//The speed that the player will move
public float turnSpeed = 60f;		//The speed at which the character turns
public float turnSmoothing = 15f;		//The turns rate of smoothness
	
private Vector3 movement;		//x,y,z movement
private Vector3 turning;		//x,y,z, turning
private Animator anim;			//Animator variable
private Rigidbody playerRigidBody;//Game objects act under control of physics

	void awake()
	{
		//Get references
		playerRigidBody = GetComponent<rigidbody>();
		anim = GetComponent<animator>();

	}
	
	void FixedUpdate()
	{
		//Store Input Axis
		float lh = Input.GetAxisRaw ("Horizontal");
		float lv = Input.GetAxisRaw ("Vertical");
		
		Move (lh, lv);
		Animating (lh, lv);

	}
	void Move (float lh, float lv)
	{
		//Move the Player
		movement.Set (lh, 0f, lv);
		movement = movement.normalized * speed * Time.deltaTime;
		playerRigidBody.MovePosition(transform.position + movement);

		
		if (lh != 0f || lv != 0f) 

		{
			Rotating (lh, lv);
		}
	}
	
	void Rotating(float lh, float lv)
		
	{
		Vector3 targetDirection = new Vector3 (lh, 0f, lv);
		Quaternion targetRotation = Quaternion.LookRotation (targetDirection, Vector3.up);
		Quaternion newRotation = Quaternion.Lerp (GetComponent <rigidbody>().rotation, targetRotation, turnSmoothing * Time.deltaTime); 
		GetComponent<rigidbody>(). MoveRotation(newRotation);
	}
	
	void Animating (float lh, float lv)
		
	{
		bool running = lh != 0f || lv != 0f;
		anim.SetBool ("IsRunning", running);
	}
	
}</rigidbody></rigidbody></animator></rigidbody>

推荐答案




这篇关于我如何修复NullReferenceException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 11:15