1
我的代碼工作得很好,直到我爲保存的健康和倖存者添加了文本。爲什麼添加文字會導致玩家移動錯誤?
現在行controller.Move(moveVelocity);由於控制器爲空,因此會出現錯誤NullRefeenceexption。
奇怪的是,如果我進入LivingEntity和註釋掉所有
Health.text或SurvivorsSaved.text它再次工作線。
任何人都知道爲什麼?
代碼:
public class Player : LivingEntity {
public float moveSpeed = 5;
Camera viewCamera;
PlayerController controller;
GunController gunController;
protected override void Start()
{
base.Start();
controller = GetComponent<PlayerController>();
gunController = GetComponent<GunController>();
viewCamera = Camera.main;
}
void Update()
{
// Movement input
Vector3 moveInput = new Vector3(Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical"));
Vector3 moveVelocity = moveInput.normalized * moveSpeed;
controller.Move(moveVelocity);
// Look input
Ray ray = viewCamera.ScreenPointToRay(Input.mousePosition);
Plane groundPlane = new Plane(Vector3.up, Vector3.zero);
float rayDistance;
if (groundPlane.Raycast(ray, out rayDistance))
{
Vector3 point = ray.GetPoint(rayDistance);
//Debug.DrawLine(ray.origin,point,Color.red);
controller.LookAt(point);
}
// Weapon input
if (Input.GetMouseButton(0))
{
gunController.Shoot();
}
}
}
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class LivingEntity : MonoBehaviour, IDamageable
{
public float startingHealth;
protected float health;
protected bool dead;
private float playerhealth=100;
private int Survivorssaved=0;
public Text Health;
public Text SurvivorsSaved;
public event System.Action OnDeath;
protected virtual void Start()
{
health = startingHealth;
Health.text = "Health: " + playerhealth;
SurvivorsSaved.text = "Survivors Saved:" + Survivorssaved;
}
public void TakeHit(float damage, RaycastHit hit)
{
TakeDamage(damage);
}
public void TakeDamage(float damage)
{
health -= damage;
if (GameObject.Equals(gameObject, GameObject.FindGameObjectWithTag("Player")))
{
playerhealth = health;
Health.text = "Health: " + playerhealth;
SurvivorsSaved.text = "Survivors Saved: " + Survivorssaved;
}
if (health <= 0 && !dead)
{
if(GameObject.Equals(gameObject, GameObject.FindGameObjectWithTag("Player")))
{
}
if (GameObject.Equals(gameObject, GameObject.FindGameObjectWithTag("Zombie")))
{
ScoreManager.Instance.AddScore(100);
}
if (GameObject.Equals(gameObject, GameObject.FindGameObjectWithTag("Survivor")))
{
ScoreManager.Instance.RemoveScore(500);
}
Die();
}
}
public void HealDamage(float damage)
{
health += damage;
playerhealth = health;
Survivorssaved += 1;
Health.text = "Health: " + playerhealth;
SurvivorsSaved.text = "Survivors Saved: " + Survivorssaved;
}
protected void Die()
{
dead = true;
if (OnDeath != null)
{
OnDeath();
}
GameObject.Destroy(gameObject);
}
}
你應該看看[mcve]的想法,特別是最小化。看起來這種情況下的問題可能與從「Player」到「PlayerController」的鏈接(在場景編輯器中)沒有設置一樣簡單。 – 31eee384
所以我進入了Unity並且雙重檢查了一切,發現了問題的根源。當我將文本對象給予玩家倖存者時,殭屍也在問這個問題,而我並沒有把它給予他們。不幸的是,現在我有一個其他的問題,因爲殭屍並不是這樣,所以我需要處理這個生物實體代碼。 – JamieC