1. 程式人生 > >Unity3d 常用的方法

Unity3d 常用的方法

ans oid 頁面 組件 initial ring 找到 count name

1、創建物體

2、加載物體

3、尋找物體

4、添加腳本

1、創建物體

  GameObject go;
    // Use this for initialization
    void Start () {
        go = new GameObject("New");
    }

find 方法查找對應的組件(找到第一個匹配的組件)

  GameObject go;
    GameObject goLight;
    Light light;
    // Use this for initialization
    void Start () {
        go 
= new GameObject("New"); goLight = GameObject.Find("Directional Light");//頁面組件 light = goLight.GetComponent<Light>(); light.color = Color.red; }

兩個燈光

    GameObject go;
    GameObject goLight;
    GameObject goLight2;
    Light light1;
    Light light2;
    
// Use this for initialization void Start () { go = new GameObject("New"); goLight = GameObject.Find("1/2/DirectionalLight"); light1 = goLight.GetComponent<Light>(); light1.color = Color.red; goLight2 = GameObject.Find("1 (1)/2/DirectionalLight"); light2
= goLight2.GetComponent<Light>(); light2.color = Color.green; }

第二種寫法(兩個燈光)

    public Transform transRoot;

    Transform translight1;
    Transform translight2;

    // Use this for initialization
    void Start () {
        
        FindChild(transRoot,"RLight",ref translight1);
        FindChild(transRoot, "GLight", ref translight2);
        translight1.GetComponent<Light>().color = Color.red;
        translight2.GetComponent<Light>().color = Color.green;
    }
    
    /// <summary>
    /// 尋找物體
    /// </summary>
    /// <param name="trans">作為父物體的transform</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,lenght=trans.childCount; i < lenght; i++)
            {
                FindChild(trans.GetChild(i),findName,ref _trans);
            }
        }
    }

Unity3d 常用的方法