如何在触发器上加载预制件以便我的游戏继续进行?

时间:2015-01-09 13:09:54

标签: c# unity3d

我正在做一个'跑步' Unity中的游戏,我正在制作一个带有球的原型,其他球跟随着他。如果追随者击中一个物体,他们会在一段时间后被摧毁。我做了一条有障碍物的道路并预先制造它们。现在我的问题是如何加载预制触发器或其他东西,以便我的游戏继续前进。目标是我不需要制作整个地图,但地图是从不同道路的预制件中随机选择的。

如果这对我主要角色的代码有帮助,我可能会在另一个触发器中加载预制件或其他东西吗?

这是我的代码。

using UnityEngine;
using System.Collections;

public class Ball : MonoBehaviour {

public float InputForce;
public GUIText guiText;
public float rotationHorizontal;
public AudioClip ACeffect2;
public GameObject zombiePrefab;

void FixedUpdate() {

    rigidbody.AddForce( Camera.main.transform.right * Input.GetAxis("Horizontal") * InputForce);
    rigidbody.AddForce( Camera.main.transform.forward * Input.GetAxis("Vertical") * InputForce);

    transform.position += Vector3.forward *InputForce * Time.deltaTime;
    rotationHorizontal = Input.GetAxis("Horizontal") * InputForce;
    rotationHorizontal *= Time.deltaTime;
    rigidbody.AddRelativeTorque (Vector3.back * rotationHorizontal);

}

void OnCollisionEnter(Collision col){
    if (col.gameObject.name == "Zombie") {
        Debug.Log ("Player geraakt, nu ben je eigenlijk dood");
    }
    if (col.gameObject.name == "Obstakel1") {
        Debug.Log ("Obstakel1 geraakt");
        audio.PlayOneShot(ACeffect2);
        InputForce = 0;
    }
    if (col.gameObject.name == "Obstakel2") {
        Debug.Log ("Obstakel2 geraakt");
    }
}

void AddZombies(int aantal){
    for (int i = 0; i < aantal; i++){
        GameObject go = GameObject.Instantiate(zombiePrefab, transform.position - new Vector3(0, 0, 7 + i),Quaternion.identity) as GameObject;
        Zombie zb = go.GetComponent<Zombie>();
        zb.target = gameObject.transform;
    }
}

void OnTriggerEnter(Collider col) {
    Debug.Log ("Enter" +col.name);
    if (col.tag == "AddZombies"){
        AddZombies(4);
    }
}

void OnTriggerExit(Collider col) {
    Debug.Log ("Leaving with" +col.name);
}
}

1 个答案:

答案 0 :(得分:3)

制作游戏对象并添加包含以下代码的组件:

public GameObject prefab; // Drag and drop prefab to component in unity

// When trigger is triggered
void OnTriggerEnter(Collider col) 
{
    Instantiate(prefab, new Vector3(0,0,0), Quaternion.Identity);
}

然后,您可以将想要实例化的预制件拖放到统一的组件中。 位置可能是您希望它产生的位置(例如transform.position使其在您放置触发器的位置产生)。

请注意,要制作一个触发器,您需要制作一个新的空游戏对象并添加您想要的对撞机。要使其调用OnTriggerEnter方法,您还需要选中对撞组件上的is trigger框。