Reputation: 15
I almost got my game done. However, I want to generate infinite enemies, like in avoider games. However, I tried researching and no luck. How can I do this? It is the only thing I need to do to finish my game.
The BlockScript.cs code (The enemy code) is the following:
using UnityEngine;
using System.Collections;
public class BlockScript : MonoBehaviour {
private GameObject wayPoint;
private Vector3 wayPointPos;
private Rigidbody2D rigidBody2D;
public bool inGround = true;
private float jumpForce = 400f;
private float speed = 6.0f;
void Start () {
wayPoint = GameObject.Find("wayPoint");
}
private void awake()
{
rigidBody2D = GetComponent<Rigidbody2D>();
}
void Update () {
if (inGround)
{
inGround = false;
rigidBody2D.AddForce(new Vector2(0f, jumpForce));
}
wayPointPos = new Vector3(wayPoint.transform.position.x, transform.position.y,
wayPoint.transform.position.z);
transform.position = Vector3.MoveTowards(transform.position,
wayPointPos, speed * Time.deltaTime);
Vector2 min = Camera.main.ViewportToWorldPoint(new Vector2(0, 0));
if(transform.position.y< min.y)
{
Destroy(gameObject);
}
}
}
Upvotes: 1
Views: 167
Reputation: 1681
The typical solution would be to store your enemy (the complete hierarchy for a GameObject
) in a prefab so that they can be re-used and instantiated from code. Then, create a reference to your prefab and instantiate it whenever you see fit. For example:
public GameObject EnemyPrefab; // assign this in editor
(...)
Instantiate(EnemyPrefab, transform.position, transform.rotation); // creates a new enemy
You will probably need to control this functionality from a separate script, not from the enemy script itself (eg. create a specialized EnemySpawner
script)
Upvotes: 1