顯示包含「Lambda」標籤的文章。顯示所有文章
顯示包含「Lambda」標籤的文章。顯示所有文章

2016年4月7日星期四

[Unity3D]用uFrame的Kernel在場景間修改玩家狀態和數據


在uFrame 1.6的 Example Project裏有一個UserManagementSystem的系統(WinCondition這個eEnum是我之後加的,下文會再討論)



public class UserManagementService : UserManagementServiceBase
{
    [Inject("LocalUser")] public UserViewModel LocalUser;

    public override void Setup()
    {
        base.Setup();
  // for develop only
  LocalUser.AuthorizationState = AuthorizationState.Authorized;
        //LocalUser.AuthorizationState = AuthorizationState.Unauthorized;
    }

    public void AuthorizeLocalUser(string Username, string Password)
    {
        if (Username == "uframe" && Password == "uframe")
        {
            Debug.Log("authorized in service");     
            LocalUser.AuthorizationState = AuthorizationState.Authorized;
        }
    }
}

這是處理Example Project內一開始登入的部份,就是確認登入成功後把AuthorizationState這個Enum轉成Authorized,方便在其他腳本檢查玩家的狀態。

我在想,是不是可以用UserManagementSystem內UserViewModel(我把這個instance命名為LocalUser, 上圖左上角)儲存玩家各種設定和資料,然後在不同場景不同的View 或 Controller的腳本把LocalUser取出來用或修改設定呢?

簡單說個例子,其中一個想做的功能就是在主畫面(有一個SetBattleScreenView)按不同作戰/勝利模式的按鈕,會修改LocalUser中WinCondition的設定,在進入作戰畫面後(另一個場景scene),而作戰畫面會檢查玩家在用哪個勝利模式(就是WinCondition),而運行不同的代碼。



(如果大家不了解uFrame MVVM模式可以來這裏了解一下:http://isaacforfun.blogspot.hk/2015/06/uframeflappy-brid.html)

2015年9月10日星期四

[Unity3D] Array與List

在學習List<T>, 其實List<T>跟Array有點相似所以問了一下Google大神,發現兩個不錯的說明

[C#] 陣列 & List<T>
https://kw0006667.wordpress.com/2013/04/03/c-陣列-listt/
下面的 code主要是抄考這篇的,只是弄了一個Unity的版本,用上Lambda真的廷方便的呀,Lumbda也是最近才學習的!左邊是參數(parameters), 右邊則是指令(instructions),這樣就不用開一個有名的function那麽麻煩!
students.Sort((x, y) => { return -x.Score.CompareTo(y.Score); });

例如這一句,(x, y)是參數,reutrn -x.Score.CompareTo(y.Score) 則是指令,這樣就可以由大到小排序了~

Array與List
http://sharecoder.blogspot.hk/2012/10/arraylist.html
//Array使用連續記憶體空間,List【不需要】使用連續記憶體空間。//
重點呀!長知識了~

好了看看測試的程式

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class Test: MonoBehaviour {
 
 public struct Student
 {
  public string Name;
  public int Score;

  public Student(string name, int score)
  {
   this.Name = name;
   this.Score = score;
  }
 }
 
 void Start()
 {
  List students = new List()
  { 
   new Student("Tim", 80),
   new Student("Jimmy", 76),
   new Student("David", 92),
   new Student("Jason", 57),
   new Student("Amy", 40)
  };
  
  // 利用 Lambda 運算式,由大到小排序
  students.Sort((x, y) => { return -x.Score.CompareTo(y.Score); });
  
  foreach (var item in students)
  {
   Debug.Log(item.Name + " : " + item.Score);
  }
 }
}

結果: