团结:敌人生成代码

时间:2016-11-27 04:50:22

标签: c# android unity3d unity5

我几乎完成了游戏。但是,我想产生无限的敌人,比如在避免游戏中。但是,我尝试过研究而没有运气。我怎样才能做到这一点?这是我完成比赛所需要做的唯一事情。

BlockScript.cs代码(敌人代码)如下:

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

    }
}

1 个答案:

答案 0 :(得分:1)

典型的解决方案是将您的敌人(GameObject的完整层次结构)存储在prefab中,以便可以从代码中重新使用和实例化它们。然后,创建对预制件的引用,并在您认为合适时实例化它。例如:

public GameObject EnemyPrefab; // assign this in editor
(...)
Instantiate(EnemyPrefab, transform.position, transform.rotation); // creates a new enemy

您可能需要从单独的脚本控制此功能,而不是从敌人脚本本身控制(例如,创建专门的EnemySpawner脚本)