2017-10-10 43 views
0

我不是程序員,但不知何故想嘗試創造某種東西,就像是一種愛好。 截至目前,我已經列出了不同的gameobjects(模型),我需要從該列表中選擇一個。一切正常,但我想看看一個人如何忍受他們的行爲可以改變選擇的一部分。從列表中獲取模型


因此,首先是我的瓦片持有信息:

using System; 
using UnityEngine; 

[Serializable] 
public class Tiles { 

public string Name; 
public Type TileType; 
public Vector3 Cordinates; 
public GameObject Tile; 

public Tiles() 
{ 
    Name = "Unset"; 
    TileType = Type.Unset; 
    Cordinates = new Vector3(0, 0, 0); 
    Tile = null; 
} 

public Tiles(string name, Type type, Vector3 cord, GameObject tile) 
{ 
    Name = name; 
    TileType = type; 
    Cordinates = cord; 
    Tile = tile; 
} 

public enum Type 
{ 
    Unset, 
    Sand, 
    Obstacle, 
    ObstaclePass 
} 

} 

而我所謂的地圖,它吸引它藏漢只是容易。在這張地圖裏面有GetTileType() - 它返回我正在繪製的那個gameobject。

using System.Collections.Generic; 
using UnityEngine; 

public class Map : MonoBehaviour { 

public Vector2 MapSize = new Vector2(5,5); 
public List<Tiles> MapTile = new List<Tiles>(); 
//AllTiles holds all the gameobject i'm choosing from 
public List<GameObject> AllTiles = new List<GameObject>(); 


public void GenerateMap() 
{ 
    for (int x = 0; x < MapSize.x; x++) 
    { 
     for (int z = 0; z < MapSize.y; z++) 
     { 
      //just so i could test if it draws different gameobject 
      if (x == 2 && z == 2) 
      { 
       MapTile.Add(new Tiles("Obstacle", Tiles.Type.Obstacle, new Vector3(x, 0, z), GetTileType(Tiles.Type.Obstacle))); 
      } 
      else 
      { 
       MapTile.Add(new Tiles("Unset", Tiles.Type.Unset, new Vector3(x, 0, z), GetTileType(Tiles.Type.Unset))); 
      } 
     } 
    } 
} 

//This is my question 
public GameObject GetTileType(Tiles.Type type) 
{ 
    switch (type) 
    { 
     case Tiles.Type.Unset: 
      return AllTiles[0]; 
     case Tiles.Type.Obstacle: 
      return AllTiles[1]; 
     case Tiles.Type.ObstaclePass: 
      return AllTiles[2]; 
     default: 
      break; 
    } 
    return AllTiles[0]; 
} 

public void DrawMap() 
{ 
    for (int i = 0; i < MapTile.Count; i++) 
    { 
     Instantiate(MapTile[i].Tile, MapTile[i].Cordinates, Quaternion.Euler(90, 0, 0), transform); 
    } 
} 

private void Start() 
{ 
    GenerateMap(); 
    DrawMap(); 
} 
} 

我真的可以使用開關或如果statment。開關看起來更好,所以我堅持下去,但不知何故,我認爲應該有更好更清潔的方式。或者我應該選擇瓷磚類瓷磚?那麼做這些的其他選擇是什麼?或者這個代碼中真正應該改變的東西。 (並不是真的想在這裏做任何事,只是每週嘗試幾次)

回答

1

我會確保AllTiles是一對一的,並與Tiles.Type對齊。

public GameObject GetTileType(Tiles.Type type) 
{ 
    return AllTiles [(int)type]; 
} 

編輯:這也會使函數調用不需要,提高性能。