我与一个对Unity有更好了解的朋友检查了这段代码,但是我们找不到问题。
基本上,Unity表示我无法为预制对象创建父对象,但是我正在尝试更改实例对象而非父对象的父对象。

我无法理解该错误(但我认为它在Update方法中)

public class WeaponsManager:MonoBehaviour, IWeapon{
private usefulStuff crax= new usefulStuff();
private bool canShoot = true;
public float projectileSpeed;
public float bulletTime;
private float t = 0f;
public Rigidbody bullet;
public int maxBullets, maxBulletsPerCharger;
private int actualBullets;
public Animation reloadAnimation;
public Transform bulletSpawn;
public Transform gunPosition;
public GameObject[] Weapons;
private GameObject actualWeapon=null;



void Awake()
{
    if (Weapons.Length == 0)
    {
        Debug.Log("No weapons loaded");
        EditorApplication.isPaused = true;
    }
}
void Update()
{
    //So i check if there aren't weapons loaded. If there aren't, i load the first Weapon      GameObject in the Weapons Array, then i instantiate it.
    if (actualWeapon == null)
    {
        actualWeapon = GameObject.Instantiate(Weapons[0], gunPosition.position,     gunPosition.rotation) as GameObject;
        actualWeapon.transform.parent = GameManager.instance.player.transform;

    }
    else // Now if there is a gun loaded, i update its position.
    {

    }
}
public virtual void Fire()
{
    //Check if the charger is full
        if(actualBullets>0){
            //Check if the player can shoot (REALLY LOL CPTN OBVIOUS STRIKEZ AGAIN )
                if(canShoot){
                    //Logic: Remove a bullet, create it then move it. Easy peasy.
                    actualBullets--;
                     Rigidbody nBullet = GameObject.Instantiate(bullet, bulletSpawn.position, Quaternion.identity)as Rigidbody;
                     nBullet.AddForce (new Vector3(Vector3.forward.x, Vector3.forward.y, projectileSpeed));
                    //And now the player cant shoot. Cause nobody wants a sniper mitra.
                     canShoot=false;
                }
                else
                {
                //All this stuff is to make a little amount of time pass between two bullets
                if(t <=bulletTime)
                    {
                    t += Time.deltaTime;
                    }
                else
                {
                    canShoot=true;
                    t = 0;
                }
            }
        }
            else
        {
        Reload();
        }
}


public void Reload () {
    canShoot = false;
    actualBullets = maxBulletsPerCharger;
    reloadAnimation.Play ();
    crax.Delay (reloadAnimation.clip.length);
    canShoot = true;

}
}

最佳答案

你的问题是

actualWeapon.transform.parent = GameManager.instance.player.transform;


试图获取未实例化的父级。您需要转到GameManager并实际实例化播放器GameObject。然后,您可以保留对玩家的引用,并使其成为玩家的武器子代。

10-07 16:03