Unity 3D - News, Help, Resources, and Conversation

r/Unity3D374.0K subscribers40 active
Why this Script not work:Question

[Image]

[Image]

this function is working on Update()

i want turn b_input to true when press LShift

How create a lobby like fall guys or fortnite on unity with mirror and steamworksQuestion

Cómo crear un lobby como Fall Guys o Fortnite en Unity con Mirror y Steamworks

How to optimize allocations if I need to randomize which prefab is instantiated?Question

According to the manual ( https://docs.unity3d.com/Manual/performance-garbage-collection-best-practices.html ), if I understand it correctly:

  • GameObjects should not be frequently instantiated / destroyed. Rather, in cases like a turret shooting bullets, the bullets should be pooled. Unity provides the ObjectPool class for this purpose.
  • Closures should be avoided. Each time a closure is called memory is allocated to the heap. Unity's garbage collector is bad at clearing up frequent tiny allocations.

My use case: I'm trying to make my own bullet hell game. Enemies will be randomly spawned at the top of the screen. Collection of enemies available to spawn will increase during gameplay, so later on more dangerous enemies will start spawning. As the player's cannon becomes more powerful and so the player may be able clear hordes of weak enemies efficiently then weak enemies may start spawning at very high rates, with more occasional powerful enemies.

Unfortunately, I have already run into performance issues with lots of enemies and bullets and so I'm trying to find their cause and resolve them.

To this end I tried to implement pooling. Currently I have something like this:

public class SpawnManager : MonoBehaviour
{
    public SpawnableEnemy[] enemyPrefabs;

    private ObjectPool<SpawnableEnemy>[] pools;

    private void Start()
    {
        pools = enemyPrefabs.Select(prefab => new ObjectPool<SpawnableEnemy>(
            createFunc: () => Instantiate(prefab),
            actionOnGet: enemy =>
            {
                enemy.gameObject.SetActive(true);
                enemy.Spawn();
            },
            actionOnRelease: enemy =>
            {
                enemy.gameObject.SetActive(false);
            },
            actionOnDestroy: enemy => Destroy(enemy)
        )).ToArray();
    }

    private void Update()
    {
        if(ShouldSpawn())
        {
            int enemyPrefabIndex = DecideWhichEnemyToSpawn();
            pools[enemyPrefabIndex].Get();
        }
    }
}

SpawnableEnemy, SpawnableEnemy.Spawn(), SpawnManager.DecideWhichEnemyToSpawn(), SpawnManager.ShouldSpawn() are my own classes / methods omitted here for brevity.

I used LINQ and created closures in SpawnManager.Start(). I thought it would be OK, since Start() executes only once and not frequently. However, the aforementioned official manual says that:

executing the closure requires allocation of an object on the managed heap.

Executing, and not just creating! So I'm going to create garbage each time I'm retrieving an enemy from the pool! I thought that an ObjectPool was meant to avoid creating garbage when I need to add a GameObject to the scene! Will this be acceptable if, late in game, we might have 8 or 16 weak enemies per second?

What is the solution to this issue? The core problem seems to me that I must create an array of ObjectPools, each passed a different createFunc that Instantiates a different prefab and so prefab is a variable from outside of the scope of the closure, which may create issues. I can't see how to resolve this as long as I use ObjectPool.

If instead of using ObjectPool I used something like a List then I wouldn't need to pass createFunc to it and so my code would, instead, look like this:

private void Start()
{
    pools = enemyPrefabs.Select(_ => new List<SpawnableEnemy>()).ToArray();
}

private void Update()
{
    if(ShouldSpawn())
    {
        int enemyPrefabIndex = DecideWhichEnemyToSpawn();
        var pool = pools[enemyPrefabIndex];

        SpawnableEnemy spawned;
        if(pool.Count == 0)
        {
            spawned = Instantiate(enemyPrefabs[enemyPrefabIndex]);
        }
        else
        {
            spawned = pool[pool.Count-1];
            pool.RemoveAt(pool.Count-1);
            spawned.SetActive(true);
        }

        spawned.Spawn();
    }
}

Now I no longer have closures.

Is this a sufficient reason not to use ObjectPool? This seems suspicious to me, since I explicitly opt out of the use of a framework-provided class for the very reason this class is provided for me to be used. So this looks like a code smell.

If not, then what am I failing to see? Is this any way to resolve this issue without avoiding ObjectPool?

Or is my reasoning incorrect and my original code does not create garbage each time an enemy is retrieved from the pool?

How to create a mountain path (terrain)Question

I cant find information or a video on the process of creating a path that will cut through this mountain

[Image]

When I try using Terrain tools "Sharpen peaks" gets me closer, but I cant make a smooth on ramp, and i dont really have much control over the path which gets created.

Maybe I have to do this the other way around, or maybe there are some tools that I am not aware of with Terrain tools which would help me achieve this, and maybe there is a process to creating a solid onboarding ramp to this path. I dont know.

-
2
1h
Local multiplayer and Gamepad inputsQuestion

Hello, I'm having troubles understanding how to work correctly with the Unity Input System and local multiplayer.

I've managed to make player spawn and be controlled one by each controller, by the way I would like ho have an instance of the controller to be passed to prefabs so that I can instantiate 4 players and then assign a controller to each not the other way around. In other words I want to decide which object is controlled by which controller.

How to Grow or Shrink a Character While Excluding Equipped Clothing and ItemsQuestion

Hi everyone, I was wondering if anyone would have a suggestions or resources for how a character could be grown or shrunk during gameplay and exclude the equipped clothing and items so they stay a constant size. For example if a knight holding a greatsword is grown, the sword will remain the same size and essential be like a dagger once done and if the knight is shrunk they will have the armor that they are wearing hang loosely on them. For equipment like swords and held items I believe I can accomplish this just by having a script attached to the equipment that allows it to follow the desired hand transform while not actually being a child of the character. The issue really arises when it comes to the clothing of the character which I want to still react to the character's animation. Thank you in advance for any suggestions that you can offer me. Hope anyone who finds this has a good day.

Physics or Raycasts? - My big noober question Question

Allo chums,

So I've been hashing out some for-fun prototypes in Unity and fell back on my old method (from my GM days) of moving the transform directly and using mini raycasts to detect collision with ground or incoming obstacles before applying new positions. I'd also typically write up various things like gravity, acceleration, edge sliding etc myself.

That being said: is there a clear advantage to using the ACTUAL physics system and Rigidbody over this? I understand the physics system is comprehensive but I haven't seen any marked reason why I should absolutely take that over just raycasting for colliders.

This probably comes down to me being a *massive* nub, but if anybody wants to Uhm Actually me, I'm keen to hear it.

15
19
17h
How to achieve this Light under door effect for VR?Question

Hi guys,

Im working on a vr project and would like to achieve a door that looks something like this:

https://www.123rf.com/photo_69005455_open-door-with-light-in-dark-room.html

The door is in an open area surrounded by water, very much like Suzume's Door. I am trying to figure out how I should go about this, in terms of baking and directional lighting and am a little overwhelmed haha. If anyone has any ideas its greatly appreciated!

Below a pic of the current door setup!

[Image]