I have been working on creating a field of view script in unity. It is very inefficient and was thrown together without consideration for performance. I decided to make it, because using the regular shadow system was what I wanted, and each object required a script. There is also a problem with the shadows being jittery. Is there anything I can do to fix it, and if not, are there other good alternatives?
Script- Basically just casts a bunch of rays and creates meshes over them.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
public class fieldofview : MonoBehaviour {
public LayerMask targetMask;
public float radius;
public int NumberOfRays;
private Vector2 LastStart;
private Vector2 LastEnd;
private bool Last;
public GameObject MeshHolder;
public GameObject Mesh;
public void Start(){
for (int i = 0; i < NumberOfRays; i++){
GameObject shadow = Instantiate(Mesh, new Vector2(0, 0), Quaternion.identity);
shadow.transform.SetParent(MeshHolder.transform);
}
}
void Update(){
for (int i = 0; i < NumberOfRays; i++){
Mesh mesh = MeshHolder.transform.GetChild(i).GetComponent<MeshFilter>().mesh;
Vector3[] vertices = mesh.vertices;
Vector3[] normals = mesh.normals;
MeshHolder.transform.GetChild(i).gameObject.SetActive(true);
var dir = Quaternion.Euler(0, 0, i * 360/NumberOfRays) * transform.right;
Vector3 startPosition = transform.position;
Vector3 endPosition = dir * radius + transform.position;
RaycastHit2D hit = Physics2D.Linecast(startPosition, endPosition, targetMask);
if(hit.collider != null){
if(Last){
Vector3[] setvertices = new Vector3[4]{
new Vector2(LastStart.x, LastStart.y),
new Vector2(LastEnd.x, LastEnd.y),
new Vector2(hit.point.x, hit.point.y),
new Vector2(endPosition.x, endPosition.y)
};
mesh.vertices = setvertices;
mesh.RecalculateBounds();
}else MeshHolder.transform.GetChild(i).gameObject.SetActive(false);
LastStart = hit.point;
LastEnd = endPosition;
Last = true;
Debug.DrawLine(hit.point, endPosition, Color.green);
}else {
Last = false;
MeshHolder.transform.GetChild(i).gameObject.SetActive(false);
}
}
}
}
Output-
I am have a problem of