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);
}
}