Hi, I’m looking for a performant way of getting all nearby objects with a specific class.
An example of what I’m trying to do:
I (the player) have a power cord. I want to turn on a light above all nearby wall sockets to indicate where I can plug the power cord into. Only sockets near me (within 10 units for example) need to turn on as I don’t care about ones in the distance. If I move too far from a nearby socket it should turn off and vice versa if I move close to another. Sockets can be instantiated/destroyed at any point while playing.
From my understanding using FindObjectsOfType and checking their distance from the player every frame isn’t too friendly on performance. Since these sockets can be spawned/despawned during play, getting a list on Awake or when the power cord is selected wouldn’t work as far as I’m aware?
You can place a sphere collider (Set trigger to true) that is 10 units in diameter around the player. You can place this object as a child of the player. The next step would be to identify these sockets. You can do that by getting a list of all object the objects the trigger is colliding with.
Player Singleton
The other solution is to add a script to the player that makes it a singleton and allow other scripts to access it easily without using "FindObjectOfType". Here is how you do it:
In your player script create a singleton the following way:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerSingletonScript : MonoBehaviour
{
public static PlayerSingletonScript Instance;
void Awake()
{
if (Instance == null)
{
Instance = this;
}
else
{
Destroy(this.gameObject);
}
}
//Rest of your code
Now this will help you to access your gameobject easily from any other script on the screen this way “PlayerSingletonScript.Instance” since Instance is a static variable.
Adding a script “SocketObject.cs”, for example, that would calculate the distance between itself and PlayerSingletonScript.Instance.transform.position and accordingly doing the action itself.