对所有spawn预制件应用相同的移动(使用List)

时间:2018-04-11 12:04:54

标签: c# unity3d

该脚本通过 InvokeRepeating 生成由预制件(多维数据集)创建的无限移动墙。如何在运行时将生成的预制件放入List中,如果它们发生碰撞则停止它们与玩家?

enter image description here

public Vector3[] positions=new Vector3[4];
public GameObject barrier;

float speed=1f;

void Start () 
{
    InvokeRepeating("SpawnBarrier",1f,speed);
}

void SpawnBarrier()
{
    for(int i=0;i<=3;i++)
    {
        Instantiate (barrier,positions[i],Quaternion.identity);
    }
}


void OnTriggerEnter(Collider other)
{
    if(other.gameObject.CompareTag("Player"))
    {
        Debug.Log ("Trigger");  
    }
}

1 个答案:

答案 0 :(得分:1)

Movement创建一个新脚本并将其附加到包含OnTriggerEnter方法和static event Action的屏障预制件:

bool canMove = true;

void OnEnable()
{
    PlayerTriggered += StopMoving;
}

void OnDisable()
{
    PlayerTriggered -= StopMoving;
}

void StopMoving()
{
    canMove = false;
}

void Update()
{
    if(canMove)
        // movement code
}

public static event System.Action PlayerTriggered;
void OnTriggerEnter(Collider other)
{
    if(other.gameObject.CompareTag("Player"))
    {
        if(PlayerTriggered != null)
            PlayerTriggered();
    }
}