Skip to content

Instantly share code, notes, and snippets.

@mylxsw
Created December 20, 2017 08:11
Show Gist options
  • Save mylxsw/ed90a400c74e4ca3fc3119f20ef8fd81 to your computer and use it in GitHub Desktop.
Save mylxsw/ed90a400c74e4ca3fc3119f20ef8fd81 to your computer and use it in GitHub Desktop.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameControl : MonoBehaviour {
public GameObject[] objects;
public Transform transform;
private int current;
private Vector3 initPos;
void Awake()
{
if (instance == null) {
instance = this;
} else {
DestroyImmediate (this);
}
}
private static GameControl instance;
public static GameControl Instance
{
get
{
if (instance == null) {
instance = new GameControl ();
}
return instance;
}
}
GameControl()
{
current = 0;
}
/**
* 获取当前展示对象的索引
*/
private int currentIndex()
{
return current;
}
/**
* 增加当前展示对象的索引
*/
private int nextIndex()
{
return ++current;
}
/**
* 切换到下一个对象
*/
public GameObject nextObject()
{
if (currentIndex() > maxIndex()) {
return null;
}
int current = currentIndex ();
int next = nextIndex ();
return destroyObject(current).newObject(next);
}
/**
* 销毁GameObject
*/
private GameControl destroyObject(int index)
{
if (index > maxIndex()) {
return this;
}
Destroy (objects [index]);
return this;
}
/**
* 创建一个新的GameObject
*/
private GameObject newObject(int index)
{
if (index > maxIndex()) {
return null;
}
if (transform != null) {
initPos = transform.localPosition;
}
GameObject obj = Instantiate (objects [index], initPos, Quaternion.identity) as GameObject;
if (!obj.activeSelf) {
obj.SetActive (true);
}
objects [index] = obj;
return obj;
}
/**
* Max index
*/
private int maxIndex()
{
return objects.Length - 1;
}
// Update is called once per frame
void Update () {
if (Input.GetKeyUp (KeyCode.Space)) {
nextObject ();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment