1. 程式人生 > >Unity做一個發射炮臺,1秒發射1個,5秒後消失的例子

Unity做一個發射炮臺,1秒發射1個,5秒後消失的例子

思路:小球要移動,移動一段時間消失,需要translate+destory;

          一個小球不夠,需要多次COPY預製體小球,copy;

一、COPY程式碼,把這個程式碼放在不是複製的球的其他物體上,然後把預製體球拖入a中

using UnityEngine;

using System.Collections;


public class copy : MonoBehaviour {

public Gameobject a;

public float t1;     //定義一個時間,可以在面板輸入,這個時間是從小球發射至小球消失的時間,為2秒時是個距離,4秒是個距離 。                                                                                                                       做個迴圈(幾秒例項化一個)

private float t2;    //定義一個後臺執行的,私有的時間。從開始執行至結束執行的時間。(這個時間用於輔助計算)

    // Use this for initialization

    void Start () {
        t2=t1;        // 把面板輸入的t1賦值給t2;
        
    }

// Update is called once per frame
void Update () {

       t2=t2-Time.deltaTime;      //把面板輸入的時間,“1”,減去0.0000X,直至為0,也就是1秒過去了,例項化複製這個小                                                                                                                        球,1秒複製1個。

       if(t2<=0){

Instantiate(a);

t2=t1;                                       //重複賦值,重複執行

}

    }

}

二、球的移動程式碼   ,把這個程式碼放在小球上

using UnityEngine;
using System.Collections;


public class QiuMove : MonoBehaviour {
    
    // Use this for initialization
    void Start () {
        Destroy(gameObject, 5.0f);                      //消失
    }

// Update is called once per frame
void Update () {
        transform.Translate(transform.right  * Time.deltaTime * 2);    //移動    
        
    }
}

三】注意預製體要在Hie中刪除

補充:

copy的第二種方法:

using UnityEngine;
using System.Collections;


public class copy : MonoBehaviour {
    public GameObject a;
    public float t1;    
    private float t2;

 void Start () {
        InvokeRepeating("CloneSphere",t1,t2); //呼叫更簡潔的例項化方法:重複執行一個方法,起始時間:幾秒後開始行; 幾秒發射一個

    }

void Update () {
    }
void CloneSphere()
    {
      Instantiate(a);
    }
}

InvokeRepeating:

1 2 3 4 InvokeRepeating(methodName: string, time: float, repeatRate: float): void; methodName:方法名 time:多少秒後執行 repeatRate:重複執行間隔
InvokeRepeating()這個方法是重複呼叫的意思,裡面還可以限定多長時間後,每過多長時間呼叫一次。