我的代码工作得很好,直到我为健康添加了文本并保存了幸存者。
现在行控制器。移动(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);
}
}
答案 0 :(得分:0)
我找到了答案,但我没有看到我将其标记为已解决,因此我将简单地发布解决方案。
当我在团结场景编辑器中检查时,正确地将playerController传递给播放器时,发现健康和幸存者获救的文本对象也被僵尸和幸存者要求,并且他们想要将信息传递给尽管没有传递文本对象,但是文本仍然存在。
我仍然没有把它传递给僵尸或幸存者,但是通过改变代码,我确保僵尸和幸存者永远不会将任何值传递给文本文件。