Unity3d創建物體,尋找物體,加載物體,添加腳本


GetCreateObject:

using UnityEngine;

public class GetCreateObject : MonoBehaviour {
    GameObject emptyGo;
    Light goLight;
    GameObject goCamera;
    public Camera pCamera;
    public Transform goRoot;
    Transform transLight;

    GameObject tank;
    
    void Start () {
        //創建物體:在當前場景中創建一個GameObject
        emptyGo = new GameObject("New");

        //尋找物體:獲取當前GameObject的Component
        goLight = GetComponent<Light>();
        goLight.color = Color.red;

        //尋找物體:獲取當前場景中其他GameObject
        goCamera = GameObject.Find("Main Camera");
        goCamera.transform.Translate(0, 1, -9);

        //創建物體:通過public屬性,在Unity中拖動控件的方式
        pCamera.transform.Translate(0, 1, 12);

        //尋找物體:通過工具方法找到物體
        FindChild(goRoot, "Light", ref transLight);
        transLight.GetComponent<Light>().color = Color.green;

        Debug.Log("Test");

        //添加腳本:用代碼方式創建GameObject並添加腳本
        tank = new GameObject("Tank");
        tank.AddComponent<Tank>();
    }

    /// <summary>
    /// 尋找物體
    /// </summary>
    /// <param name="trans">作為父物體的tranform</param>
    /// <param name="findName">名稱</param>
    /// <param name="_trans">找到的物體</param>
    void FindChild(Transform trans, string findName, ref Transform _trans)
    {
        if (trans.name.Equals(findName))
        {
            _trans = trans.transform;
            return;
        }
        if (trans.childCount != 0)
        {
            for(int i = 0, length = trans.childCount; i < length; i++)
            {
                FindChild(trans.GetChild(i), findName, ref _trans);
            }
        }
    }
}

Tank:

using UnityEngine;

public class Tank : MonoBehaviour {

    //加載物體:拖動方式得到預置體
    public GameObject goBullet;
    private GameObject bullet;

    //加載物體:用資源加載方式得到預置體,這種方式下資源要放在Assets/Resources文件夾下
    private GameObject mBullet;
    private GameObject myBullet;

    // Use this for initialization
    void Start () {
        mBullet = Resources.Load("Bullet") as GameObject;
    }
    
    // Update is called once per frame
    void Update () {
        if (Input.GetButtonDown("Fire1"))
        {
            //讓預置體生成在場景中
            bullet = Instantiate(goBullet);
            bullet.transform.parent = this.transform;
        } else if(Input.GetButtonDown("Fire2")) {
            myBullet = Instantiate(mBullet);
            myBullet.transform.parent = this.transform;
        }
    }
}

Bullet:

using UnityEngine;

public class Bullet : MonoBehaviour {

    Vector3 fwd;

    // Use this for initialization
    void Start () {
        //向前向量
        fwd = transform.TransformDirection(Vector3.forward);
    }
    
    // Update is called once per frame
    void Update () {
        //給一個向前的力,打出去
        GetComponent<Rigidbody>().AddForce(fwd * 1000);
    }
}

參數如圖:

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM