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

参数如图:

 

 

 

 

posted @ 2017-05-07 10:10  观海云不远  阅读(5020)  评论(0编辑  收藏  举报