跳到主要內容

Unity 近三個月的整理..Part1

最近公司製作了客製化的APP 在IOS PAD上執行 ,這篇算是做一個使用到的一些功能整理,順便回顧一下自己寫的程式囉。(一定要在用到更多OO的寫法 不然太亂了 加油!)


1.在Unity中 我們假如想要 讓程式去新增的元件可以做成Prefab 而且 美術也可以直接更動Prefab的內部細項(例如Prefab中的攝影機鏡頭 材質等等)

而如果我們假如要對Prefab掛載Script就可以先新增一個Empty GameObject然後把Prefab放在這Object之下。

但是假如是要用Instantiate這個方法的話,就看是不是要用程式去掛載Listener了,例如:var obj = Instantiate(PrefabName); obj.GetComponent<Button>().onClick.AddListener(doSomethingsFuction());

以下為補充程式碼:
  
  public int index;
  private Button myselfButton;
 
  void Start()
  {
      myselfButton = GetComponent(Button)();
      myselfButton.onClick.AddListener(() => actionToMaterial(index));
  }
 
  void actionToMaterial(int idx)
  {
      Debug.Log("change material to HIT  on material :  " + idx);
  }
  //移除偵聽RemoveListener
  void Destroy()
  {
       myselfButton.onClick.RemoveListener(() => actionToMaterial(index));
  }

2.Object.Instantiate 他可以動態新增物件 可以去把她掛在在場景中某個父物件下面,設定位置跟旋轉角度,public static Object Instantiate(Object original, Vector3 position, Quaternion rotation, Transform parent);這功能其實就像FALSH裡面的 AddChild。
 
private GameObject obj;

public void whateverFuction()
{
  obj = null;  //清空GameObject
  obj = Instantiate(PrefabPartCar); //塞入Prefab
} 

3.在程式一開始會用useing去連結到其他隻有著namespace的程式

而在public class TextStatement : MonoBehaviour, IPointerEnterHandler monobehaviour後面的IPointerEnterHandler是interface,而interface在建構的時候裡面會有一些function而在其他支程式要用到這個interface的時候也必須要有interface中的這隻fuction。

例如現在有一個interface叫做(狗) 而(狗)會有守家的這個功能,而我在另一個地方新增一個(家)裡面去新增(狗)interface 然而在家這個程式中下面一定要有守家的這個function 這樣程式才能working。
 
//最裏頭的namespace
using System;
using System.Collections.Generic;

namespace UnityEngine.EventSystems
{
    public class PointerEventData : BaseEventData
    {
      public List hovered;
      public PointerEventData(EventSystem eventSystem);

      public InputButton button { get; set; }
      //我只抓一個來當示範而已
    }
}

// 這裡為interface,撰寫者可自行命名,在這裡使用到PointerEventData 類別
namespace UnityEngine.EventSystems
{
    public interface IPointerDownHandler : IEventSystemHandler
    {
        void OnPointerDown(PointerEventData eventData);
    }
}

//應用面
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.EventSystems;

public class UIButtonTrigger3DModel : MonoBehaviour, IPointerDownHandler, IPointerExitHandler
{
    public void OnPointerExit(PointerEventData eventData)
    {
        Debug.Log("false");
        ButtonTrigger = false;
    }
}

有空還是要再釐清這些用法
補充:https://dotblogs.com.tw/feegg333/2011/06/13/28232

4.我現在來背一下monobehaviour的生命週期:
1.awake 
2.onEnable 
3.start 
4.updateing 
5.yield WaitForSeconed 
6.ondisable 
7.ondestroy 

目前是用到這些而已啦。這類別並不是C#既有的 而是unity才有的。
詳細資訊:https://docs.unity3d.com/ScriptReference/MonoBehaviour.html

5.關於TWEEN,自己有寫一個可以TWEEN 角度 位置 大小 長寬,但發現有一個也不錯用,就是ITWEEN。紀錄一下用法

iTween.ScaleTo(advencedContainer, Vector3.one, tweenDuration);  
iTween.RotateTo(allow, new Vector3(0f, 0f, 180f), tweenDuration);
他還可以TWEEN聲音等等的。

他的方法就是(TWEEN的物件,TWEEN的數值,TWEEN的時間),但就可能要再寫他的TWEEN的模式就完美了。

留言