【问题标题】:I don't see what is wrong with the script to instantiate a prefab我看不出实例化预制件的脚本有什么问题
【发布时间】:2017-06-02 01:37:57
【问题描述】:

我看不出这段代码有什么问题。它说变量 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);
                }
            }

        }
    }

【问题讨论】:

    标签: unity3d


    【解决方案1】:

    您必须区分您创建的弹丸(克隆)和用于复制的弹丸(预制)

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-01
      • 2015-04-06
      • 2014-06-29
      • 2013-09-18
      • 1970-01-01
      • 1970-01-01
      • 2020-11-21
      • 2020-01-01
      相关资源
      最近更新 更多