Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine.UI;
- public class ObjektSelect : MonoBehaviour {
- public UnitManager unitManager; //ссылка на скрипт информации о юнитах и присвоение ей переменной чтобы использовать в данном скрипте
- public BuildManager buildManager; //ссылка на скрипт строительства .-.-.-.-.-.-.-.-.
- public Texture2D SelectTexture;//картинка рамки выделения
- public GameObject TargetPrefab;//префаб цели к которой будут двигатся юниты
- public GameObject ResursTargetPrefab;
- private List<ISelect> selectObjects = new List <ISelect>();
- private Vector3 ?firstPoint = null;
- public Canvas menu;
- private byte m = 0;
- private byte Mm = 0;
- private int idType, idType1,IdType2;
- public Button[] buttons = new Button[6];
- public List<UnitType> typeselection;
- public GameObject panel;
- public ImageDictionary[] imageDictionary;
- private GameObject gotex;
- private GameObject Panelgotex;
- private void Start()
- {
- typeselection = new List<UnitType>();
- for (int i = 0; i < panel.transform.childCount; i++)
- {
- buttons[i] = (panel.transform.GetChild(i).GetComponent<Button>());
- }
- idType = idType1= IdType2= 0;
- HideButtons();
- Panelgotex = GameObject.Find("PanelOpisania");
- gotex = GameObject.Find("Opisanies");
- Panelgotex.GetComponent<Image>().enabled = false;
- gotex.GetComponent<Text>().enabled = false;
- if (unitManager == null)
- {
- unitManager = GetComponent<UnitManager>();
- }
- if (buildManager == null)
- {
- buildManager = GetComponent<BuildManager>();
- }
- }
- public void ChoseGroupFromSelection(int id)
- {
- for (int i = 0; i < selectObjects.Count; i++)
- {
- if (selectObjects[i].GetUnitType != typeselection[id])
- {
- selectObjects[i].OnDeSelect();
- selectObjects.Remove(selectObjects[i]);
- i--;
- }
- }
- HideButtons();
- typeselection.Clear();
- ShowButtons();
- }
- void ShowButtons()
- {
- for (int i = 0; i < typeselection.Count; i++)
- {
- buttons[i].image.sprite = ImageDictionary.GetSprite(imageDictionary, typeselection[i]);//запускаем в структуре функцию которая возвращает картинку подобранную по типу
- buttons[i].image.color = new Color(1, 1, 1, 1);
- buttons[i].interactable = true;
- if (buttons[i].GetComponentInChildren<Text>() != null && UnitType.Rab == typeselection[i] )
- {
- buttons[i].GetComponentInChildren<Text>().text = idType.ToString();
- }
- if (buttons[i].GetComponentInChildren<Text>() != null && UnitType.Voin == typeselection[i] )
- {
- buttons[i].GetComponentInChildren<Text>().text = IdType2.ToString();
- }
- if (buttons[i].GetComponentInChildren<Text>() != null && UnitType.Shaha == typeselection[i] )
- {
- buttons[i].GetComponentInChildren<Text>().text = idType1.ToString();
- }
- }
- }
- void BuildIk()
- {
- foreach (Unit dd in selectObjects)
- {
- if (dd.GetComponent<UnitRab>()!=null)
- {
- int id = dd.GetComponent<UnitRab>().ID;
- switch (id)
- {
- case 1: // Рабочие
- idType++;
- break;
- case 2: // если айди равен двум Хз кто)
- idType1++;
- break;
- }
- }
- if (dd.GetComponent<UnitVoin>() == true)
- {
- Debug.Log("D");
- int idVoin = dd.GetComponent<UnitVoin>().ID;
- if (idVoin == 3) { IdType2++; }//Воины
- }
- }
- }
- void HideButtons()
- {
- for (int i = 0; i < buttons.Length; i++)
- {
- if (buttons[i] != null)
- { // проверка на случай, если кнопок меньше чем размер массива
- buttons[i].image.color = new Color(1, 1, 1, 0);
- buttons[i].interactable = false;
- buttons[i].image.sprite = null;
- if (buttons[i].GetComponentInChildren<Text>() != null)
- {
- buttons[i].GetComponentInChildren<Text>().text = null;
- }
- }
- }
- }
- [System.Serializable]
- public struct ImageDictionary
- {
- public UnitType unitType;
- public Sprite sprite;
- public static Sprite GetSprite(ImageDictionary[] idict, UnitType unitType)
- {
- Sprite spr = null;
- for (int i = 0; i < idict.Length; i++)
- {
- if (idict[i].unitType == unitType)
- {
- spr = idict[i].sprite;
- break;
- }
- }
- return spr;
- }
- public ImageDictionary(UnitType _unitType, Sprite _sprite)
- {
- unitType = _unitType;
- sprite = _sprite;
- }
- }
- public void TestClick()
- {
- Mm++;
- if (Mm == 1)
- {
- Debug.Log("AAAAAAAA");
- Time.timeScale = 0;
- }
- if (Mm == 2)
- {
- Debug.Log("BBBBBbb");
- Mm = 0;
- Time.timeScale = 1;
- }
- }
- private void Update ()
- {
- if (idType == 0)
- {
- }
- if (Input.GetKeyUp(KeyCode.Escape))
- {
- HideButtons();
- }
- if (Input.GetKeyUp(KeyCode.Escape))
- {
- m++;
- if (m == 1)
- {
- if (menu.GetComponent<Canvas>().enabled == false)
- {
- Debug.Log("НАЖАЛ");
- menu.GetComponent<Canvas>().enabled = true;
- }
- }
- if (m == 2)
- {
- if (menu.GetComponent<Canvas>().enabled == true)
- {
- Debug.Log("ВЫШЕЛ");
- menu.GetComponent<Canvas>().enabled = false;
- }
- m = 0;
- Time.timeScale = 1;
- }
- }
- if(GameStat.actionState == ActionState.Free)
- {
- if(Input.GetMouseButtonDown(0))
- {
- RaycastHit hit = CastFromCursor();
- if(hit.transform != null)
- {
- if(hit.transform.tag == "Ground" || hit.transform.tag == "Unit")//если нажали на землю или юнита то передаём позицию мыши от которой будет создаватся рамка выделения
- {
- if (GameStat.actionState == ActionState.Free)
- {
- buildManager.SelectBuild = GetComponent<Build>();
- selectObjects.Remove(buildManager.SelectBuild);
- }
- firstPoint = Input.mousePosition;
- }
- if(hit.transform.tag == "Build")//если нажали на здание то рамка создаватся не будет потому что позиция мышки не передаётся в переменную фёрст поинт()
- {
- buildManager.SelectBuild = hit.transform.GetComponent<Build>();
- selectObjects.ForEach(x => x.OnDeSelect());//лямда выражение цыкл запускается для каждого юнита и вызывается функция OnDeSelect то что они теперь не выделены
- selectObjects.Clear();//и выделеные юниты очистятся с масива
- selectObjects.Add(buildManager.SelectBuild);
- hit.transform.SendMessage("OnSelect",(object)1);
- }
- if (hit.transform.tag == "MainBuild")//если нажали на здание то рамка создаватся не будет потому что позиция мышки не передаётся в переменную фёрст поинт()
- {
- buildManager.SelectBuild = hit.transform.GetComponent<Build>();
- selectObjects.ForEach(x => x.OnDeSelect());//лямда выражение цыкл запускается для каждого юнита и присваивается функция OnDeSelect то что они теперь не выделены
- selectObjects.Clear();//и выделеные юниты очистятся с масива
- selectObjects.Add(buildManager.SelectBuild);
- hit.transform.SendMessage("OnSelect", (object)1);
- }
- }
- }
- if(selectObjects.Count > 0 && Input.GetMouseButtonDown(1))
- {
- RaycastHit hit = CastFromCursor();
- if(hit.transform.tag == "Ground")
- {
- GameObject target = Instantiate(TargetPrefab, hit.point,Quaternion.identity)as GameObject;//создаём префаб цели
- if(target != null)
- {
- selectObjects.ForEach(x => x.OnSetTarget (target));
- }
- }
- else
- {
- GameObject targetPosition = hit.collider.gameObject;
- if (targetPosition != null)
- {
- selectObjects.ForEach(x => x.OnSetTarget(targetPosition));
- }
- }
- }
- if(firstPoint != null && Input.GetMouseButtonUp(0))
- {
- for (int i = 0; i < buttons.Length; i++)
- {
- if (buttons[i] != null)
- { // проверка на случай, если кнопок меньше чем размер массива
- buttons[i].image.color = new Color(1, 1, 1, 0);
- buttons[i].interactable = false;
- buttons[i].image.sprite = null;
- if (buttons[i].GetComponentInChildren<Text>() != null)
- {
- buttons[i].GetComponentInChildren<Text>().text = null;
- }
- }
- } ///////////////////////////////////////////////////////////////////////////////////////////
- selectObjects.ForEach(x => x.OnDeSelect());
- selectObjects.Clear();
- idType = idType1 = IdType2 = 0;
- typeselection.Clear();
- ShowButtons();
- Check((Vector3)firstPoint, Input.mousePosition);
- firstPoint = null;
- }
- }
- if(firstPoint !=null && GameStat.actionState == ActionState.Build)
- {
- firstPoint = null;
- }
- }
- private RaycastHit CastFromCursor ()
- {
- Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
- RaycastHit hit;
- Physics.Raycast (ray,out hit);
- Debug.DrawLine(ray.origin, hit.point, Color.yellow);
- return hit;
- }
- private void OnGUI()
- {
- if(firstPoint != null && SelectTexture != null)
- {
- GUI.DrawTexture(GetRectFromPoint((Vector3)firstPoint,Input.mousePosition),SelectTexture);
- }
- }
- private Rect GetRectFromPoint(Vector3 one , Vector3 two)
- {
- float height = two.x - one.x;
- float width = (Screen.height - two.y)- (Screen.height - one.y);
- return new Rect (one.x, Screen.height - one.y, height,width);
- }
- private void Check (Vector3 firstPoint, Vector3 endPoint)
- {
- if(endPoint.x < firstPoint.x)
- {
- var x1 = firstPoint.x;
- var x2 = endPoint.x;
- firstPoint.x = x2;
- endPoint.x = x1;
- }
- if(endPoint.y > firstPoint.y)
- {
- var y1 = firstPoint.y;
- var y2 = endPoint.y;
- firstPoint.y = y2;
- endPoint.y = y1;
- }
- Rect rect = GetRectFromPoint ((Vector3)firstPoint, endPoint);
- foreach (Unit unit in unitManager.GetAllUnits())
- {
- Vector3[] points = { unit.GetComponent<Collider>().bounds.max,unit.GetComponent<Collider>().bounds.min,unit.transform.position};
- foreach(Vector3 point in points)
- {
- Vector3 screenPoint = Camera.main.WorldToScreenPoint(point);
- screenPoint = new Vector3(screenPoint.x,Screen.height - screenPoint.y, screenPoint.z);
- if(rect.Contains(screenPoint))
- {
- selectObjects.Add(unit);
- unit.SendMessage("OnSelect", selectObjects.Count);
- break;
- }
- }
- }
- for (int i = 0; i < selectObjects.Count; i++)
- {
- if (!typeselection.Contains(selectObjects[i].GetUnitType))
- {
- typeselection.Add(selectObjects[i].GetUnitType);
- }
- }
- BuildIk();
- ShowButtons();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement