隨機範例(未使用ref,沒有返回值):
using UnityEngine; using System.Collections; using System.Collections.Generic; using System.Linq; public class codetrain001 : MonoBehaviour { public int condition = 0; public int[] Number = new int[10] { 60, 145, 56, 90, 75, 70, 97, 63, 81, 32 }; // Use this for initialization void Start() { //Debug.Log("condition is " + condition); Oncaculation(); int Max_number = Number.Max(); int Min_number = Number.Min(); if (condition >= 3) { Debug.Log("Max is " + Max_number); } else { Debug.Log("Min is " + Min_number); } } public int Oncaculation() { condition = Random.Range(0, 5); if (condition == 0) { Debug.Log("狀況0"); } else if (condition == 1) { Debug.Log("狀況1"); } else if (condition == 2) { Debug.Log("狀況2"); } else if (condition == 3) { Debug.Log("狀況3"); } else if (condition == 4) { Debug.Log("狀況4"); } return condition; } }
隨機範例(使用ref,有返回值):
引用參數ref
int為值類型,值類型參數如果想達到引用類型參數的效果,需要用到引用修飾符ref
(有用new初始化的類型,使用new後才真正開闢內存空間)
如果不使用ref,外部Oncaculation();內的condition(實參)將不會受到Oncaculation()方法的condition(形參)賦值
using UnityEngine; using System.Collections; using System.Collections.Generic; using System.Linq; public class codetrain001 : MonoBehaviour { public int condition = 0; public int[] Number = new int[10] { 60, 145, 56, 90, 75, 70, 97, 63, 81, 32 }; // Use this for initialization void Start() { //Debug.Log("condition is " + condition); Oncaculation(ref condition); int Max_number = Number.Max(); int Min_number = Number.Min(); if (condition >= 3) { Debug.Log("Max is " + Max_number); } else { Debug.Log("Min is " + Min_number); } } public int Oncaculation(ref int condition) { condition = Random.Range(0, 5); if (condition == 0) { Debug.Log("狀況0"); } else if (condition == 1) { Debug.Log("狀況1"); } else if (condition == 2) { Debug.Log("狀況2"); } else if (condition == 3) { Debug.Log("狀況3"); } else if (condition == 4) { Debug.Log("狀況4"); } return condition; } }