I have a simple system in my 2d game that allows the player to select units, similar many other games.
I decided that the best way for the player to determine what units are selected is to simply draw triangles over each unit.
I decided to have a UI graphic component do the drawing, and it works flawlessly. But especially when you moving the camera, you can notice lag between the position of the unit and the triangle. here’s what i have so far:
using UnityEngine;
using UnityEngine.UI;
using System.Collections.Generic;
public class drawUnitSelections : Graphic{
public List<Vector2> points;
protected override void OnPopulateMesh(VertexHelper vh){
Color32 color32 = color;
vh.Clear();
//remove empties from list
for(int i=0;i<points.Count;i++){
vh.AddVert(points[i], color32, new Vector2(0f, 0f));
vh.AddVert(points[i]+new Vector2(7,10), color32, new Vector2(0f, 1f));
vh.AddVert(points[i]+new Vector2(-7,10), color32, new Vector2(1f, 1f));
vh.AddTriangle(i*3, i*3+1, i*3+2);
}
}
void Update(){
if(Application.isPlaying&&Time.frameCount%1==0){
points.Clear();
for(int i=UnitManager.main.selectedUnits.Count-1;i>=0;i--){
Vector3 point = UnitManager.main.selectedUnits[i].transform.position;
points.Add(Camera.main.WorldToScreenPoint(point+new Vector3(0,1.2f)));
}
SetAllDirty();//causes the mesh to be redrawn a frame or two later, causing the lag
}
}
}
OnPopulateMesh doesn’t seem to update on its own, even when i change the points, so i discovered that adding a SetAllDirty() causes OnPopulateMesh to be run again, but a frame too late, which causes lag.
The documentation on graphic doesn’t help at all. In fact it doesn’t even note the existence of OnPopulateMesh, or any other functions that could be useful. Thanks for the source @LeftyRighty
So what should I do? and is doing it like this the right way? (cause looping through all the selected units seems slow to me, but I don’t see any other way of doing this)
I would greatly appreciate any suggestions. thanks.