Advertisement
Guest User

Untitled

a guest
Feb 26th, 2017
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 13.93 KB | None | 0 0
  1. using UnityEngine;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using UnityEngine.UI;
  5.  
  6.  
  7. public class ObjektSelect : MonoBehaviour {
  8.  
  9.     public UnitManager unitManager; //ссылка на скрипт информации о юнитах и присвоение ей переменной чтобы использовать в данном скрипте
  10.     public BuildManager buildManager; //ссылка на скрипт строительства .-.-.-.-.-.-.-.-.
  11.     public Texture2D SelectTexture;//картинка рамки выделения
  12.     public GameObject TargetPrefab;//префаб цели к которой будут двигатся юниты
  13.     public GameObject ResursTargetPrefab;
  14.  
  15.     private List<ISelect> selectObjects = new List <ISelect>();
  16.    
  17.     private Vector3 ?firstPoint = null;
  18.     public Canvas menu;
  19.     private byte m = 0;
  20.     private byte Mm = 0;
  21.     private int idType, idType1,IdType2;
  22.  
  23.     public Button[] buttons = new Button[6];
  24.     public List<UnitType> typeselection;
  25.     public GameObject panel;
  26.     public ImageDictionary[] imageDictionary;
  27.    
  28.  
  29.     private GameObject gotex;
  30.      private GameObject Panelgotex;
  31.  
  32.  
  33.  
  34.  
  35.  
  36.     private void Start()
  37.     {
  38.        
  39.             typeselection = new List<UnitType>();
  40.         for (int i = 0; i < panel.transform.childCount; i++)
  41.         {
  42.             buttons[i] = (panel.transform.GetChild(i).GetComponent<Button>());
  43.         }
  44.  
  45.         idType = idType1= IdType2= 0;
  46.  
  47.  
  48.         HideButtons();
  49.        
  50.  
  51.  
  52.  
  53.         Panelgotex = GameObject.Find("PanelOpisania");
  54.         gotex = GameObject.Find("Opisanies");
  55.         Panelgotex.GetComponent<Image>().enabled = false;
  56.         gotex.GetComponent<Text>().enabled = false;
  57.  
  58.         if (unitManager == null)
  59.         {
  60.             unitManager = GetComponent<UnitManager>();
  61.         }
  62.         if (buildManager == null)
  63.         {
  64.             buildManager = GetComponent<BuildManager>();
  65.         }
  66.  
  67.     }
  68.  
  69.     public void ChoseGroupFromSelection(int id)
  70.     {
  71.  
  72.         for (int i = 0; i < selectObjects.Count; i++)
  73.         {
  74.             if (selectObjects[i].GetUnitType != typeselection[id])
  75.             {
  76.                 selectObjects[i].OnDeSelect();
  77.                 selectObjects.Remove(selectObjects[i]);
  78.                 i--;
  79.  
  80.             }
  81.         }
  82.        HideButtons();
  83.        
  84.         typeselection.Clear();
  85.         ShowButtons();
  86.  
  87.     }
  88.  
  89.     void ShowButtons()
  90.     {
  91.         for (int i = 0; i < typeselection.Count; i++)
  92.         {
  93.             buttons[i].image.sprite = ImageDictionary.GetSprite(imageDictionary, typeselection[i]);//запускаем в структуре функцию которая возвращает картинку подобранную по типу
  94.             buttons[i].image.color = new Color(1, 1, 1, 1);
  95.             buttons[i].interactable = true;
  96.             if (buttons[i].GetComponentInChildren<Text>() != null && UnitType.Rab == typeselection[i] )
  97.             {
  98.                 buttons[i].GetComponentInChildren<Text>().text = idType.ToString();
  99.             }
  100.             if (buttons[i].GetComponentInChildren<Text>() != null && UnitType.Voin == typeselection[i] )
  101.             {
  102.                 buttons[i].GetComponentInChildren<Text>().text = IdType2.ToString();
  103.             }
  104.             if (buttons[i].GetComponentInChildren<Text>() != null && UnitType.Shaha == typeselection[i] )
  105.             {
  106.                 buttons[i].GetComponentInChildren<Text>().text = idType1.ToString();
  107.             }
  108.         }
  109.     }
  110.     void BuildIk()
  111.     {
  112.  
  113.         foreach (Unit dd in selectObjects)
  114.         {
  115.             if (dd.GetComponent<UnitRab>()!=null)
  116.             {
  117.                 int id = dd.GetComponent<UnitRab>().ID;
  118.                 switch (id)
  119.                 {
  120.                     case 1: // Рабочие
  121.                         idType++;
  122.                    
  123.                         break;
  124.  
  125.                     case 2: // если айди равен двум Хз кто)
  126.                         idType1++;
  127.                    
  128.                         break;
  129.          
  130.                 }
  131.             }
  132.  
  133.             if (dd.GetComponent<UnitVoin>() == true)
  134.             {
  135.                 Debug.Log("D");
  136.                 int idVoin = dd.GetComponent<UnitVoin>().ID;
  137.                 if (idVoin == 3) { IdType2++; }//Воины
  138.             }
  139.  
  140.         }
  141.  
  142.  
  143.     }
  144.     void HideButtons()
  145.     {
  146.         for (int i = 0; i < buttons.Length; i++)
  147.         {
  148.             if (buttons[i] != null)
  149.             { // проверка на случай, если кнопок меньше чем размер массива
  150.                 buttons[i].image.color = new Color(1, 1, 1, 0);
  151.                 buttons[i].interactable = false;
  152.                 buttons[i].image.sprite = null;
  153.                 if (buttons[i].GetComponentInChildren<Text>() != null)
  154.                 {
  155.                     buttons[i].GetComponentInChildren<Text>().text = null;
  156.                 }
  157.             }
  158.         }
  159.     }
  160.  
  161.     [System.Serializable]
  162.     public struct ImageDictionary
  163.     {
  164.         public UnitType unitType;
  165.         public Sprite sprite;
  166.         public static Sprite  GetSprite(ImageDictionary[] idict, UnitType unitType)
  167.         {
  168.             Sprite spr = null;
  169.             for (int i = 0; i < idict.Length; i++)
  170.             {
  171.                 if (idict[i].unitType == unitType)
  172.                 {
  173.                     spr = idict[i].sprite;
  174.                    
  175.                     break;
  176.                 }
  177.             }
  178.             return spr;
  179.         }
  180.  
  181.         public ImageDictionary(UnitType _unitType, Sprite _sprite)
  182.         {
  183.             unitType = _unitType;
  184.             sprite = _sprite;
  185.         }
  186.     }
  187.  
  188.     public void TestClick()
  189.     {
  190.         Mm++;
  191.         if (Mm == 1)
  192.         {
  193.            
  194.                 Debug.Log("AAAAAAAA");
  195.                
  196.                 Time.timeScale = 0;
  197.  
  198.            
  199.         }
  200.  
  201.         if (Mm == 2)
  202.         {
  203.            
  204.                 Debug.Log("BBBBBbb");
  205.            
  206.             Mm = 0;
  207.             Time.timeScale = 1;
  208.         }
  209.     }
  210.     private void Update ()
  211.     {
  212.  
  213.         if (idType == 0)
  214.         {
  215.  
  216.         }
  217.  
  218.         if (Input.GetKeyUp(KeyCode.Escape))
  219.         {
  220.             HideButtons();
  221.         }
  222.  
  223.  
  224.             if (Input.GetKeyUp(KeyCode.Escape))
  225.         {
  226.             m++;
  227.             if (m == 1)
  228.             {
  229.                 if (menu.GetComponent<Canvas>().enabled == false)
  230.                 {
  231.                    
  232.                      
  233.  
  234.                    
  235.                     Debug.Log("НАЖАЛ");
  236.                     menu.GetComponent<Canvas>().enabled = true;
  237.                    
  238.                 }
  239.             }
  240.  
  241.             if (m == 2)
  242.             {
  243.                 if (menu.GetComponent<Canvas>().enabled == true)
  244.                 {
  245.                     Debug.Log("ВЫШЕЛ");
  246.                     menu.GetComponent<Canvas>().enabled = false;
  247.                    
  248.                 }
  249.                 m = 0;
  250.                 Time.timeScale = 1;
  251.             }
  252.  
  253.         }
  254.  
  255.  
  256.  
  257.         if(GameStat.actionState == ActionState.Free)
  258.         {
  259.             if(Input.GetMouseButtonDown(0))
  260.             {
  261.                 RaycastHit hit = CastFromCursor();
  262.                 if(hit.transform != null)
  263.                 {
  264.                     if(hit.transform.tag == "Ground" || hit.transform.tag == "Unit")//если нажали на землю или юнита то передаём позицию мыши от которой будет создаватся рамка выделения
  265.                     {
  266.                         if (GameStat.actionState == ActionState.Free)
  267.                         {
  268.                             buildManager.SelectBuild = GetComponent<Build>();
  269.                             selectObjects.Remove(buildManager.SelectBuild);
  270.                         }
  271.                         firstPoint = Input.mousePosition;
  272.                     }
  273.                     if(hit.transform.tag == "Build")//если нажали на здание то рамка создаватся не будет потому что позиция мышки не передаётся в переменную фёрст поинт()
  274.                     {
  275.                         buildManager.SelectBuild = hit.transform.GetComponent<Build>();
  276.                         selectObjects.ForEach(x => x.OnDeSelect());//лямда выражение  цыкл запускается для каждого юнита и вызывается функция OnDeSelect то что они теперь не выделены
  277.                         selectObjects.Clear();//и выделеные юниты очистятся с масива
  278.                         selectObjects.Add(buildManager.SelectBuild);
  279.                         hit.transform.SendMessage("OnSelect",(object)1);
  280.                     }
  281.                     if (hit.transform.tag == "MainBuild")//если нажали на здание то рамка создаватся не будет потому что позиция мышки не передаётся в переменную фёрст поинт()
  282.                     {
  283.                         buildManager.SelectBuild = hit.transform.GetComponent<Build>();
  284.                         selectObjects.ForEach(x => x.OnDeSelect());//лямда выражение  цыкл запускается для каждого юнита и присваивается функция OnDeSelect то что они теперь не выделены
  285.                         selectObjects.Clear();//и выделеные юниты очистятся с масива
  286.                         selectObjects.Add(buildManager.SelectBuild);
  287.                         hit.transform.SendMessage("OnSelect", (object)1);
  288.                     }
  289.  
  290.                 }
  291.             }
  292.        
  293.               if(selectObjects.Count > 0 && Input.GetMouseButtonDown(1))
  294.                     {
  295.                         RaycastHit hit = CastFromCursor();
  296.                         if(hit.transform.tag == "Ground")              
  297.                       {
  298.                           GameObject target = Instantiate(TargetPrefab, hit.point,Quaternion.identity)as GameObject;//создаём префаб цели                       
  299.                           if(target != null)
  300.                          
  301.                             {
  302.                               selectObjects.ForEach(x => x.OnSetTarget (target));
  303.                             }
  304.                          
  305.                          }
  306.                         else
  307.                         {
  308.                             GameObject targetPosition = hit.collider.gameObject;                        
  309.                             if (targetPosition != null)
  310.                             {
  311.                                
  312.                                 selectObjects.ForEach(x => x.OnSetTarget(targetPosition));
  313.                             }
  314.                         }
  315.  
  316.                    }
  317.        
  318.         if(firstPoint != null && Input.GetMouseButtonUp(0))
  319.                      {
  320.                 for (int i = 0; i < buttons.Length; i++)
  321.                 {
  322.                     if (buttons[i] != null)
  323.                     { // проверка на случай, если кнопок меньше чем размер массива
  324.                         buttons[i].image.color = new Color(1, 1, 1, 0);
  325.                         buttons[i].interactable = false;
  326.                         buttons[i].image.sprite = null;
  327.                         if (buttons[i].GetComponentInChildren<Text>() != null)
  328.                         {
  329.                             buttons[i].GetComponentInChildren<Text>().text = null;
  330.                         }
  331.                     }
  332.                 }                                                  ///////////////////////////////////////////////////////////////////////////////////////////
  333.                 selectObjects.ForEach(x => x.OnDeSelect());
  334.                          selectObjects.Clear();
  335.                 idType = idType1 = IdType2 = 0;
  336.                 typeselection.Clear();
  337.                 ShowButtons();
  338.                 Check((Vector3)firstPoint, Input.mousePosition);
  339.                          firstPoint = null;
  340.                       }
  341.         }
  342.  
  343.         if(firstPoint !=null && GameStat.actionState == ActionState.Build)
  344.         {
  345.             firstPoint = null;
  346.         }
  347.        
  348.     }
  349.  
  350.     private RaycastHit CastFromCursor ()
  351.     {
  352.        
  353.         Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
  354.         RaycastHit hit;
  355.         Physics.Raycast (ray,out hit);
  356.         Debug.DrawLine(ray.origin, hit.point, Color.yellow);
  357.         return hit;
  358.     }
  359.  
  360.     private void OnGUI()
  361.     {
  362.        
  363.  
  364.         if(firstPoint != null && SelectTexture != null)
  365.         {
  366.             GUI.DrawTexture(GetRectFromPoint((Vector3)firstPoint,Input.mousePosition),SelectTexture);
  367.  
  368.         }
  369.     }
  370.  
  371.     private Rect GetRectFromPoint(Vector3 one , Vector3 two)
  372.     {
  373.         float height = two.x - one.x;
  374.         float width  = (Screen.height - two.y)- (Screen.height - one.y);
  375.         return new Rect (one.x, Screen.height - one.y, height,width);
  376.     }
  377.     private void Check (Vector3 firstPoint, Vector3 endPoint)
  378.     {
  379.         if(endPoint.x < firstPoint.x)
  380.         {
  381.             var x1 = firstPoint.x;
  382.             var x2 = endPoint.x;
  383.             firstPoint.x = x2;
  384.             endPoint.x = x1;
  385.         }
  386.         if(endPoint.y > firstPoint.y)
  387.         {
  388.             var y1 = firstPoint.y;
  389.             var y2 = endPoint.y;
  390.             firstPoint.y = y2;
  391.             endPoint.y = y1;
  392.         }
  393.         Rect rect = GetRectFromPoint ((Vector3)firstPoint, endPoint);
  394.         foreach (Unit unit in unitManager.GetAllUnits())
  395.         {
  396.             Vector3[] points = { unit.GetComponent<Collider>().bounds.max,unit.GetComponent<Collider>().bounds.min,unit.transform.position};
  397.             foreach(Vector3 point in points)
  398.             {
  399.                 Vector3 screenPoint =  Camera.main.WorldToScreenPoint(point);
  400.                 screenPoint = new Vector3(screenPoint.x,Screen.height - screenPoint.y, screenPoint.z);
  401.                 if(rect.Contains(screenPoint))
  402.                 {
  403.                     selectObjects.Add(unit);
  404.                     unit.SendMessage("OnSelect", selectObjects.Count);
  405.                     break;
  406.                 }
  407.             }
  408.            
  409.         }
  410.         for (int i = 0; i < selectObjects.Count; i++)
  411.         {
  412.  
  413.             if (!typeselection.Contains(selectObjects[i].GetUnitType))
  414.             {
  415.                 typeselection.Add(selectObjects[i].GetUnitType);
  416.  
  417.             }
  418.         }
  419.         BuildIk();
  420.         ShowButtons();
  421.        
  422.  
  423.     }
  424. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement