Search Unity

Enemy Control

Discussion in '2D' started by wishingchain, May 23, 2018.

  1. wishingchain

    wishingchain

    Joined:
    Oct 5, 2016
    Posts:
    25
    Hey guys. I just made a script that is supposed to randomly spawn enemies at 1 of four spawn points but its only spawning at 1 spawn point and the enemy that is supposed to follow the player that was working before the spawner was added isnt working either. These are the scripts I am using.
    Script1. The Spawner Script
    Script2. The Enemy Script

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class Spawner : MonoBehaviour {
    6.  
    7.     public Transform[] spawnPoints;
    8.     public GameObject[] monsters;
    9.     int randomSpawnPoint, randomMonster;
    10.     public static bool spawnAllowed;
    11.  
    12.     // Use this for initialization
    13.     void Start () {
    14.         spawnAllowed = true;
    15.         InvokeRepeating("SpawnAMonster", 0f, 1f);
    16.     }
    17.    
    18.     // Update is called once per frame
    19.     void Update() {
    20.  
    21.     }
    22.    
    23.     void SpawnAMonster()
    24.     {
    25.         if (spawnAllowed)
    26.         {
    27.             randomSpawnPoint = Random.Range(0, spawnPoints.Length);
    28.             randomMonster = Random.Range(0, monsters.Length);
    29.             Instantiate(monsters[randomMonster], spawnPoints[randomSpawnPoint].position, Quaternion.identity);
    30.  
    31.         }
    32.     }
    33. }
    34.  
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class EnemyController : MonoBehaviour {
    6.  
    7.     public float speed;
    8.     public Transform target;
    9.  
    10.     public Vector2 SpawnPoint;
    11.  
    12.     // Use this for initialization
    13.     void Start () {
    14.         target = GameObject.FindGameObjectWithTag("Player").GetComponent<Transform>();
    15.     }
    16.    
    17.  
    18.  
    19.     // Update is called once per frame
    20.     void Update () {
    21.  
    22.         transform.position = Vector2.MoveTowards(transform.position, target.position, speed * Time.deltaTime);
    23.  
    24.     }
    25.  
    26.     //void OnCollisionEnter2D(Collision2D collision)
    27.         //if (collision.gameObject.tag == "Player")
    28.             //Destroy(collision.collider.gameObject)
    29.  
    30.     void OnTriggerEnter2D(Collider2D col)
    31.     {
    32.         if(col.tag == "Player")
    33.         {
    34.             col.transform.position = SpawnPoint;
    35.         }
    36.     }
    37. }
    38.  
    Thanks.