user8077453
user8077453

Reputation: 15

I don't see what is wrong with the script to instantiate a prefab

I don't see what's wrong with this code. It says that the variable projectileEnemy is not assigned to anything, even though i was going to assign to it the prefab through the inspector window but the inspector window won't update because there's an error.

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

        }
    }

Upvotes: 0

Views: 46

Answers (1)

Hellium
Hellium

Reputation: 7346

You must distinguish between the projectile you create (the clone) and the one you use to make a copy from (the prefab)

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

}

Upvotes: 4

Related Questions