關於官方教程Space Shooter子彈生成部分提示MissingReferenceException的解決辦法
阿新 • • 發佈:2019-01-23
Space Shooter 第七節中子彈生成部分提示Error
MissingReferenceException: The object of type 'GameObject' has been destroyed but you are still trying to access it.
嘗試呼叫的專案GameObject已被銷燬
具體表現為當螢幕中所有子彈都因越過邊界被銷燬時,應用於子彈生成的GameObject卻顯示為bolt(clone)(clone)(clone)(clone),專案不存在導致Error。
但按照官方教程的嚴謹性應該不會出現這樣低階的錯誤。
解決方法如下(僅修改第18,28,29行處即可):
using UnityEngine; using System.Collections; [System.Serializable] public class Boundary { public float xMin, xMax, zMin, zMax; } public class PlayerController : MonoBehaviour { public float speed; public float tilt; public Boundary boundary; public GameObject bolt; public GameObject shotSpawn; public float fireRate; private float nextFire; void Update () { if (Input.GetKey("space") && Time.time > nextFire && shotSpawn != null) { GameObject shot = Instantiate(bolt) as GameObject; shot.name = bolt.name; nextFire = Time.time + fireRate; shot.transform.position = shotSpawn.transform.position; } } void FixedUpdate () { float moveHorizontal = Input.GetAxis ("Horizontal"); float moveVertical = Input.GetAxis ("Vertical"); Vector3 movement = new Vector3 (moveHorizontal, 0.0f, moveVertical); GetComponent<Rigidbody>().velocity = movement * speed; GetComponent<Rigidbody>().position = new Vector3 ( Mathf.Clamp (GetComponent<Rigidbody>().position.x, boundary.xMin, boundary.xMax), 0.0f, Mathf.Clamp (GetComponent<Rigidbody>().position.z, boundary.zMin, boundary.zMax) ); GetComponent<Rigidbody>().rotation = Quaternion.Euler (0.0f, 0.0f, GetComponent<Rigidbody>().velocity.x * -tilt); } }