上一篇博客中DiskFactory留下一个缺陷,不知你们记得没有。
现在我们来改进它,这里我们使用到的技术是场景单实例实现。首先建立一个Singleton.cs文件,文件内容如下:
public class Singleton<T> : MonoBehaviour where T : MonoBehaviour{
protected static T instance;
public static T Instance
{
get
{
if(instance == null)
{
instance = (T)FindObjectOfType(typeof(T));
if(instance == null)
{
Debug.LogError("An instance of " + typeof(T) + " is needed in the scene, but there is none.");
}
}
return instance;
}
}
}
改变下DiskFactory
public class DiskFactory : MonoBehaviour//改动点1
{
private static DiskFactory _instance;
public SceneController sceneControler { get; set; }
public List<GameObject> used;
public List<GameObject> free;
// Use this for initialization
public static DiskFactory getInstance()
{
if (_instance == null)
{
_instance = Singleton<DiskFactory>.Instance;//改动点2
_instance.used = new List<GameObject>();
_instance.free = new List<GameObject>();
}
return _instance;
}
这样就行啦。No!No!No!,既然是Mono了那就要挂在场景中才能找得到。我把它挂在摄像机那里。
然后讨论下序列化,写个DiskData然后挂在预制脚本那里,使得脚本具有相应的属性。
public class DiskData2 : MonoBehaviour {
public float size;//大小
public Color color;//颜色
public float speed;//速度
}
在检视面板就可以看到了
如何获得这些属性呢?如何将属性和GameObject关联起来呢?对了,就是GetComponent<脚本名>().属性名
DiskFactory改动点3
switch (round)
{
case 1:
newDisk.GetComponent<DiskData2>().size = 0.8f;
newDisk.GetComponent<DiskData2>().color = Color.green;
newDisk.transform.localScale = new Vector3(newDisk.GetComponent<DiskData2>().size, newDisk.GetComponent<DiskData2>().size, newDisk.GetComponent<DiskData2>().size);
newDisk.GetComponent<Renderer>().material.color = newDisk.GetComponent<DiskData2>().color;
break;
case 2:
newDisk.GetComponent<DiskData2>().size = 0.7f;
newDisk.GetComponent<DiskData2>().color = Color.yellow;
newDisk.transform.localScale = new Vector3(newDisk.GetComponent<DiskData2>().size, newDisk.GetComponent<DiskData2>().size, newDisk.GetComponent<DiskData2>().size);
newDisk.GetComponent<Renderer>().material.color = newDisk.GetComponent<DiskData2>().color;
break;
case 3:
newDisk.GetComponent<DiskData2>().size = 0.6f;
newDisk.GetComponent<DiskData2>().color = Color.red;
newDisk.transform.localScale = new Vector3(newDisk.GetComponent<DiskData2>().size, newDisk.GetComponent<DiskData2>().size, newDisk.GetComponent<DiskData2>().size);
newDisk.GetComponent<Renderer>().material.color = newDisk.GetComponent<DiskData2>().color;
break;
}
最后看下文件组织结构和场景情况
这周就到这里了,好累,我只想葛优瘫了。