unity – Detecting Surrounding GameObjects

Some Background Context:

So I have a 2D prototype in Unity I am working on that has enemy entities that have rigidbody2D component set as dynamic as I am using physics (AddForce()) for movement. I am using physics for movements as I want entities to have a physicsy feeling (slight accel / decel movement, knock back when hit / from explosions, etc.) and Unity physics system with support what I need and I would not really be able to create something myself anyways.

I want my enemies to be able to have knowledge about the entities around it (relatively large area, anywhere from 10 – 25 Unity units radius) and my initial implementation was a quick and simple trigger collider that called a script any time a GameObject in a matching layer entered or exited which worked at first. When I stress tested with a lot of entities in the same area, I noticed the performance when down exponentially with Physics2D.FindNewContacts() taking up a ton of time in the profile. Because the detection collider is on a game object under the enemy entity that has the dynamic rigidbody2D component, each new entities in the area exponentially adds more contacts (when I have 4 entities moving in range of each other that is 4 entities re-calculating contact points for 3 other entities and then I have 30 entities moving in range of each other that is 30 entities re-calculating contact points for 29 other entities and so on).

The only 2 options I can think of are:

  • Use a kinematic Rigidbody2D and write custom code for handling “physics” interactions
  • Remove the detection collider and do area scanning in a different way.

Option #1 seems like a lot of work especially since I don’t really need anything outside of what unity physics support (it is really just the performance which I assume is more just because of how I am doing things) so I am thinking of how to handle Option #2.

What I am thinking of doing at a high level is:

  • Remove the detection collider
  • Add a queue for a detection area scanning (for lack of a better term) that game objects can add themselves to or remove themselves from
  • I can process this queue in a co-routine or something (it does not need to check every frame for every entity that need detection scanning) so that each frame I do a scan for X entities
  • This detection scanner would call something like Physics2D.CircleCastAll() and then process those hits (in the same way the detection script did when using the collider).

For content, this scanning is mainly for AI purposes. Right now it is just for enemies to be able to track the player when in range however it will be expanded upon later (like enemies keep track of nearby enemies to heal if possible as one example).

Does this seem like a sane way to handle this kind of problem? Is there “standard” way of handling something like this? Am I missing something with the core problem that could solve this issue easier?

c# – Unity Event destroys all GameObjects if there are more than two listeners

I’ve been writing a system where, if a raycast hits a 2D gameObject, a UnityEvent is fired and the Shot() method is executed. It works fine if the amount of listeners receiving the callback is equal to one, in this situation it destroys only clicked GameObject (which is what I need). As soon as you add another callback (AudioSource, Playing Particles), it destroys all GameObjects, which I don’t want to be destroyed.

Class with Event:

public class ItemRaycastHit :  MonoBehaviour
{
    (SerializeField) private UnityEvent _shot;
    void Update()
    {
        if(Input.GetMouseButtonDown(0)) 
        {
            Vector2 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition); 
            RaycastHit2D hit = Physics2D.Raycast(mousePos, Vector2.zero); 
            if (hit.collider.TryGetComponent<ClickableObject>(out ClickableObject clickable)) 
            {
                _shot?.Invoke();
            }
        }
    }
}

public class ClickableObject : MonoBehaviour
{
    public void Shot()
    {
        Destroy(gameObject);
    }
}

Image of the clickable object in inspector

Inspector screenshot

c# – Unity Event destroy’s all gameObject’s if the ammount of callbacks is more than two

I’ve been writing a system where a raycast hit’s a 2D gameObject, if it does a Unity Event is fired and the Shot() method is executed. It works fine if the ammount of callbacks is equal to one, in this situation it destroys only clicked gameObject(Which is what I need).As soon as you add another callback(AudioSource, Playing Particles), it destroys all gameObjects, which i don’t want to be destroyed. Class with Event:

public class ItemRaycastHit :  MonoBehaviour
{
(SerializeField) private UnityEvent _shot;
void Update()
{
    if(Input.GetMouseButtonDown(0)) 
    {
        Vector2 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition); 
        RaycastHit2D hit = Physics2D.Raycast(mousePos, Vector2.zero); 
        if (hit.collider.TryGetComponent<ClickableObject>(out ClickableObject clickable)) 
        {
            _shot?.Invoke();
        }
    }
}
}

public class ClickableObject : MonoBehaviour
{
public void Shot()
{
    Destroy(gameObject);
}

}

Image of the clickable object in inspector

enter image description here

How to detect ray cast collision on terrain gameobjects?

How to detect ray cast collision on terrain gameobjects? – Game Development Stack Exchange

unity – Should map labels be gameobjects or on a canvas?

I want to label the countries in my game, like in the picture below.

enter image description here

Should the country names be normal unity game objects, or should they live as a textmeshpro on a canvas?

For what it’s worth, I don’t want the labels to be interactable – clicking on them should bypass the label itself and act as if the user had clicked on whatever is below them.

unity – Clearing a List and Destroying the GameObjects simulataneously

        //clear all block sprites away
        for (int i = 0; i < blockSprites.Count; i++)
        {
            Destroy(blockSprites(i));
        }
        blockSprites.Clear();

I am a little confused on deleting objects in a List. I realise that clearing the list doesn’t destroy the gameobject in Unity. Hence i have written the above routine to destroy and remove.

But what if I only wanted to destroy some of the elements (a variable amount). In that scenario the List.Clear() function wouldn’t work, would I have to make another list of indexes in order to go through destroying and removing from the list in two sweeps. Or is there a better way?

Many thanks for your time.

architecture – Organising gameobjects into multiple lists

I have a very simple little game that consists of a player, zombies, food, and treasure. It’s all automated. The player will walk towards a zombie and shoot within a certain distance, which costs energy. If the player goes below a certain energy level, it will find the closest food item and walk towards that and once the player has reached it, the player will gain energy, and continue to move towards zombies and shoot them, until all are dead and the player will movie towards the zombie.

This is meant to be a way of learning object oriented programming for a class, so standard functional concepts such as ECS do not apply (and its so simple that would be overkill). Currently I have an array of GameObjects that all other objects such as player, zombie etc inherit from that gives them a position and an image to render (I’m aware an object shouldn’t be responsible for its own rendering). All GameObjects are put into this array so I can interate through it and rendering everything which works fine. But not every entity requires an update, so I made an updatable interface, allowing classes that require updating to implement. So now i’m in a situation where there are two lists, renderable game objects, and updatable game objects. My problem arises when the player must operate on a specific subset of entities at a time. e.g. find all the zombies or all the food items to determine which is the closest. So would it be better then, to have arrays of zombies, and arrays of food items instead that I can pass to the player to operate on? And since only 2-3 game objects will need to actually be updated, should I just not bother putting them into a list to be updated and just keep a list of all renderables, with seperate lists for all zombies and food items etc?

Any thoughts on how this could be best designed would be appreciated.

Memory managing fully removing an item from a dictionary of GameObjects – Unity

When you have a dictionary that looks like Dictionary<string,GameObject> dictionaryOfGameObjects, for removing an item from the dictionary, do you have to Destroy(gameObject) and dictionaryOfGameObject.Remove(stringid) as well?

Unity – Align 2 gameObjects by their center point

I’m trying to align 2 game objects using their respective center points at runtime in Unity. The goal is to center my new generated object (SKY) to my map (terrain) which represents the center of my scene. What I already achieved is:

  • create my game object (terrain)
  • create 2 float values xCubes and zCubes based on the terrain bounds
  • create a new Game Object (SKY)
  • spawning a prefab on each xCubes and zCubes to create the ceiling

Now I need to center SKY on my terrain gameobject with bounds.min.x but the new object results aligned by its origin point, not by its center. SKY has to be aligned by x and z values but not on the Y, for which i need to specify my own value (that’s why i cannot use simply bounds.center.

    private void GenerateCeiling(int xMax, int zMax)
{
    GameObject landscape = new GameObject("SKY");

    for (int z = 0; z < zMax; z++)
    {
        for (int x = 0; x < xMax; x++)
        {
            var newCeiling = Instantiate(skyTile, new Vector3(x * 10, 0, z * 10), Quaternion.Euler(0, 0, 0));
            newCeiling.transform.parent = landscape.transform;
        }
    }
    
    landscape.AddComponent<Renderer>();
    Renderer SkyRenderer = landscape.AddComponent<Renderer>();
    var skyCenter = SkyRenderer.bounds.center;
    //landscape.transform.position = new Vector3(terrain.bounds.min.x, 50, terrain.bounds.min.z);
    skyCenter = new Vector3(terrain.bounds.min.x, 50, terrain.bounds.min.z);


    Debug.Log(terrain.bounds.size.x.ToString());
    Debug.Log(terrain.bounds.size.z.ToString());

}

i tried to deal with different renderer.bounds min, max, center, extents etc. and to create new Rendere component on the SKY game Object but it doesn’t work.

Anyone can help please?

enter image description here

How to organize GameObjects into logical groups in a Unity Scene?

Obviously there are a Scene hierarchy, but the problem is that the scene hierarchy was not meant for organizing GameObjects because parent GameObjects affect the transformation of their children.

For example what can one do to select all the decoration GameObjects? Some might be children of non-decoration GameObjects and buried very deep in the scene hierarchy while others might be root GameObjects.

One solution could be to add a Tag, but since Unity restrict you to only one tag per GameObject, that makes the usage of tags pointless as I have different overlapping categories.

Another solution would be to name objects but that is very error prone as a typing mistake will loose my GameObject. Also the team need to memorize possible tokens in the name which allow even more room for human errors.

Another solution would be to add an identifying Component, similar to how tags work in most other applications. But will there be a penalty in build time/runtime in a large project because of the additional Scripts (Components)?

Any other ideas how I can organize my Scene so that I can easily select a logical group of GameObjects from different unrelated parents in the editor Scene or Hierarchical view?

DreamProxies - Cheapest USA Elite Private Proxies 100 Private Proxies 200 Private Proxies 400 Private Proxies 1000 Private Proxies 2000 Private Proxies 5000 Private Proxies ExtraProxies.com - Buy Cheap Private Proxies Buy 50 Private Proxies Buy 100 Private Proxies Buy 200 Private Proxies Buy 500 Private Proxies Buy 1000 Private Proxies Buy 2000 Private Proxies ProxiesLive.com Proxies-free.com New Proxy Lists Every Day Proxies123.com Buy Cheap Private Proxies; Best Quality USA Private Proxies