几个小时我现在遇到这些问题:
NullReferenceException:未将对象引用设置为对象的实例 EnemyScreenSpaceUIScript.Start()(在Assets / Scripts / EnemyScreenSpaceUIScript.cs:34)
NullReferenceException:未将对象引用设置为对象的实例 EnemyScreenSpaceUIScript.Update()(在Assets / Scripts / EnemyScreenSpaceUIScript.cs:47)
第34行在Start() - Method(我添加了注释)
第47行是Update() - Method
中的第一行这是我的EnemyScreenSpaceUIScript:
public EnemyScript enemyScript;
public Canvas canvas;
public GameObject healthPrefab;
public float healthPanelOffset = 0.35f;
public GameObject healthPanel;
public Text enemyName;
private Slider healthSlider;
private DepthUIScript depthUIScript;
private Renderer selfRenderer;
// Use this for initialization
void Start ()
{
GameObject CanvasObj = GameObject.Find("HealthPrefab");
canvas = CanvasObj.GetComponent<Canvas>();
enemyScript = GetComponent<EnemyScript>();
healthPanel = Instantiate(healthPrefab) as GameObject;
healthPanel.transform.SetParent(canvas.transform, false);
enemyName = healthPanel.GetComponentInChildren<Text>();
enemyName.text = enemyScript.monsterName; // <- this is line 34
healthSlider = healthPanel.GetComponentInChildren<Slider>();
depthUIScript = healthPanel.GetComponent<DepthUIScript>();
canvas.GetComponent<ScreenSpaceCanvasScript>().AddToCanvas(healthPanel);
selfRenderer = GetComponentInChildren<Renderer>();
}
// Update is called once per frame
void Update ()
{
healthSlider.value = enemyScript.HP / (float)enemyScript.maxHP; //<- this is line 47
Vector3 worldPos = new Vector3(transform.position.x, transform.position.y + healthPanelOffset, transform.position.z);
Vector3 screenPos = Camera.main.WorldToScreenPoint(worldPos);
healthPanel.transform.position = new Vector3(screenPos.x, screenPos.y, screenPos.z);
float distance = (worldPos - Camera.main.transform.position).magnitude;
depthUIScript.depth = -distance;
float alpha = 3 - distance / 4.0f;
depthUIScript.SetAlpha(alpha);
if (selfRenderer.isVisible && alpha > 0)
{
healthPanel.SetActive(true);
}
else
{
healthPanel.SetActive(false);
}
if (gameObject.GetComponent<Mob>().health <= 0)
{
healthPanel.SetActive(false);
}
else
{
}
}
我无法弄清楚出了什么问题?