Unity: Attach Prefab Transform to Scene Object by Script

How do I get multiple zombie Prefab to chase the Player? i.e. how do I get the zombie Prefab to select the Player in Scene through script? (nav mesh requires a target, Transform) (I attached the Player Prefab before, but the zombies didn't chase, just idled).

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

public class Zombie : MonoBehaviour {

    public GameObject zombiePrefab;
    public Transform zombieArmy;
    public Transform zombieSpawnPoint;
    private Transform[] spawnPositions;
    public bool reSpawn = false;
    private bool lastToggle = false;

    // Use this for initialization
    void Start () {
        spawnPositions = zombieSpawnPoint.GetComponentsInChildren<Transform>();
    }

    private void NewSpawn()   //spawn location of newZombie
    {
        if (reSpawn)
        {
            int i = Random.Range(1, spawnPositions.Length);
            transform.position = spawnPositions[i].transform.position;
            Instantiate(zombiePrefab, transform.position, transform.rotation);

        }
    }


    void Update () { //T-toggle
        if (reSpawn != lastToggle)
        {
            NewSpawn();
            reSpawn = false;
        }
        else
            lastToggle = reSpawn;
    }
}

1 answer

  • answered 2017-06-17 18:48 BenSmith

    Solved with this:

                public Transform target;                                // target to aim for
                public GameObject player; 
    
                private void Start()
                {
    
                    player = GameObject.FindGameObjectWithTag("Player");
                    target = player.transform;