我不知道脚本实例化预制件有什么问题

时间:2017-06-01 17:32:49

标签: unity3d

我不知道这段代码有什么问题。它说变量projectileEnemy没有分配给任何东西,即使我打算通过检查员窗口为它分配预制件但是检查员窗口不会因为出现错误而更新。

   using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;

    public class Attack : MonoBehaviour {
        public Transform playerPos = null;
        private float playerDist;
        public GameObject projectileEnemy = null;

        private void Shoot()
        {
            GameObject projectileEnemy = Instantiate(projectileEnemy, transform.position, Quaternion.identity) as GameObject;
        }




        void Update () {
            playerDist = playerPos.position.x - transform.position.x;

            if (playerDist <= (3) && playerDist >= (-3))

            {
                Shoot();

                if (playerDist < (0))
                {
                    projectileEnemy.GetComponent<Rigidbody>().AddForce(transform.left * 10);
                }
                else
                {
                    projectileEnemy.GetComponent<Rigidbody>().AddForce(transform.right * 10);
                }
            }

        }
    }

1 个答案:

答案 0 :(得分:4)

您必须区分创建(克隆)的弹丸和用于制作副本的弹丸(预制件)

// Assin in the inspector the prefab of the projectile
public GameObject projectileEnemyPrefab ;

private GameObject projectileClone ;

private void Shoot()
{
   // Clone the prefab to create the real projectile of the enemy which will be propelled
    projectileClone = Instantiate(projectileEnemyPrefab , transform.position, Quaternion.identity) as GameObject;
}

void Update () {
    playerDist = playerPos.position.x - transform.position.x;

    if (playerDist <= (3) && playerDist >= (-3))

    {
        Shoot();

        if (playerDist < (0))
        {

            // Propel the instantiated **clone**
            projectileClone .GetComponent<Rigidbody>().AddForce(transform.left * 10);
        }
        else
        {
            // Propel the instantiated **clone**
            projectileClone .GetComponent<Rigidbody>().AddForce(transform.right * 10);
        }
    }

}