- Home /
How can I Disable all but one renderer in an array?
I am making a project in which the ship closest to this gameobject can render a line, but all the others cannot. I have an array of all the ships. How can I disable the line renders in all of the others ships. (Hope this made sense)
public class ShipRadar : MonoBehaviour
{
public GameObject renderers;
private GameObject[] multipleShips;
public Transform closestShip;
public bool shipContact;
// Start is called before the first frame update
void Start()
{
closestShip = null;
shipContact = false;
}
// Update is called once per frame
void Update()
{
InvokeRepeating("getClosestShip", 1, 1);
}
public Transform getClosestShip()
{
GameObject[] multipleShips = GameObject.FindGameObjectsWithTag("Ship");
float ClosestDistance = Mathf.Infinity;
Transform trans = null;
foreach (GameObject go in multipleShips)
{
float currentDistance;
currentDistance = Vector3.Distance(transform.position, go.transform.position);
if(currentDistance < ClosestDistance)
{
ClosestDistance = currentDistance;
trans = go.transform;
}
}
return trans;
}
}
Answer by Hellium · Feb 08, 2021 at 01:30 PM
First of all, do not call InvokeRepeating in Update. InvokeRepeating already handles the timing for you.
Secondly, don't use InvokeRepeating. It's bad for performances (one call is fine though) and not refactor-friendly. Either use a coroutine or Update directly in your case.
FOLLOWING CODE NOT TESTED
public class ShipRadar : MonoBehaviour
{
private float timer;
void Update()
{
timer += Time.deltaTime;
if(timer > 1)
{
timer -= 1;
GetClosestShip();
}
}
public Transform GetClosestShip()
{
GameObject[] ships = GameObject.FindGameObjectsWithTag("Ship");
float closestShipDistance = Mathf.Infinity;
Renderer closestShip = null;
foreach (GameObject ship in ships)
{
// Prefer sqrMagnitude over magnitude / distance when possible
float currentDistance = (transform.position - ship.transform.position).sqrMagnitude;
Renderer shipRenderer = ship.GetComponent<Renderer>();
if(currentDistance < closestShipDistance)
{
closestShipDistance = currentDistance;
if(closestShip != null)
closestShip.enabled = false;
closestShip = shipRenderer;
closestShip.enabled = true;
}
else
{
shipRenderer.enabled = false;
}
}
return closestShip.transform;
}
}
Oh, I see what you did. That is working well, however, I want to disable/enable the line renderer not the sprite renderer.
Replace Renderer closestShip = null;
by LineRenderer closestShip = null;
And Renderer shipRenderer = ship.GetComponent<Renderer>();
by LineRenderer shipRenderer = ship.GetComponent<LineRenderer>();
(supposing the LineRenderer
is attached to the ship. If not, you may need to call GetComponentInChildren
or similar)
Now none of the lines are appearing.. Any tips?