#archived-code-advanced

1 messages · Page 61 of 1

bleak citrus
#

you can just copypaste a C# implementation

sly grove
#

I still disagree with your characterization of random not "fully filling" the area though .

#

By definition it will give you a uniform distribution

#

it just won't guarantee no overlaps

bleak citrus
#

yeah

#

it will do a great job of filling it up

#

you could place things on a grid and then do a few steps of spring-force relaxation or something

sly grove
#

the amount of "filled" just depends on how many items you actually place.

bleak citrus
#

well, not spring-force

#

just repulsion

remote drift
sly grove
#

you'll get that with Random.Range - you just won't get overlap prevention

remote drift
#

nah, I need exactly this poisson disk or something similiar

remote drift
#

all right, this poisson disk is really cool

#

also was lucky to find 100 line static script

mellow plinth
#

Question:
For a game with "fishes" that moves using physics (moves the water), what would fit better? Grid-based fluids or Particle-based fluids? Water may also be mixed with other fluids. Or, otherwise how would you calculate the propulsion produced by the movements of the fins (fishes would be procedurally made)?

sly grove
#

how realistic does this really need to be?

bleak citrus
#

modeling the actual physics of swimming sounds miserable

compact ingot
#

i'd say the key to stuff like this is figuring out what parts of the simulation are meaningful for gameplay/immersion, use trickery to fake them or simulate coarsely and ditch all the rest

mellow plinth
#

Actually, it's no game, just a hobby project idea.
I wanted to make small creatures that lives in an aquatic environment and evolve with random mutations.
I thought that having the move with actual physics would be interesting.

sly grove
#

It might be interesting

#

it will also be extremely difficult

mellow plinth
#

I guess I will have to minimize my project idea into something more feasible then.
My main goal is using neural networks for their behaviors 😄, the rest was basically "add-ons" for the core project

timber flame
#

To implement undo/redo functionalities in a voxel city building game (editor), do you think it is more suitable to use command pattern or memento?
Because the number of voxels is huge (200,200,200) voxels. Memento keeps the states instead of actions

sly grove
#

Whatever results in less memory use is probably better.

timber flame
mellow plinth
#

Not sure if my opinion matters, but I think Command Pattern fits better for a undo/redo system.
If you only wanted to save one snapshot, then Memento, but that doesn't sounds like your idea.

fresh finch
#

Can anyone point me towards further reading for how a game like Risk of Rain 2 uses a composite pattern to make roguelike upgrades that stack with eachother?

#

They seem to do it REALLY well. Everything is so damn well coded

#

Another example would be the binding of isaac, ROUNDS, etc...

bleak citrus
#

perhaps you could have, for each "property" you want to have, a list of items

#

and a corresponding method that's called with the current value and that returns the new value

#

so, each item would register itself with the appropriate properties

#

so an item that makes you deal double damage would put itself in the "damage modifier" list

#

and then the game would call everything in that list in sequence to figure out how much damage to do

mellow plinth
# sly grove Seems like overkill and also computationally prohibitive to do actual fluid simu...

Just found this game (https://store.steampowered.com/app/1133120/Ecosystem/) which surprisingly is about fishy creatures, real swimming physics, evolution and also use a neural network 😄

Ecosystem isn't just a video game version of the laws of ecology with pre-made fish models. The simulation actually determines the creatures in the game: their bodies, how they swim, and how they think and behave. All the creatures in the trailer evolved on their own in the game; none were hand-edited!Virtual creatures evolve on their own to ada...

Price

$19.99

Recommendations

279

▶ Play video
#

I wonder how they managed that 🤔

#

Their blog says they have some problems with their creatures because game engines usually ignore conservation of angular momentum... but apart from that they don't seem to explain what they did.

indigo spoke
#

Hey guys, I need some help if you don't mind. I've been stuck on this for a while now.
Given a camera position and angle, how do I calculate the necessary FOV to cover a distance (d) on a plane?

compact ingot
indigo spoke
compact ingot
#

to do that you just need to multiply it with the sine of the angle (if it is parallel to the camera-forward, it is 0 * d, if it is orthogonal to the camera-forward it is 1 * d)

indigo spoke
indigo spoke
# compact ingot atan is in radians too

You mean I should do this? Doesn't seem to work either :/

                    var distanceToCenter = PC2DUtils.GetCameraDistanceFromWorldPlane(GameCamera.transform, WorldPlane);
                    var angle = Mathf.Atan((dProjected / distanceToCenter) * Mathf.Deg2Rad) * 2f;
                    GameCamera.fieldOfView = Mathf.Clamp(angle, .1f, 179.9f);
compact ingot
indigo spoke
compact ingot
#

also you need to potentially convert between vertical/horizontal FOV based on your aspect

indigo spoke
compact ingot
#

what values do you have for d, eulerAngles.x and distanceToCenter?

indigo spoke
#

This is the actual thing in Unity

compact ingot
#

depending on which way you want the calculation to go

indigo spoke
compact ingot
#

well the center distance isn't actually the right distance

indigo spoke
compact ingot
indigo spoke
compact ingot
#

i think there is a parameter missing, potentially another tan that scales distance to center based on angle a

indigo spoke
compact ingot
indigo spoke
compact ingot
indigo spoke
compact ingot
#

thats not the midpoint of d, thats the center of the view

indigo spoke
compact ingot
indigo spoke
compact ingot
indigo spoke
compact ingot
# indigo spoke I bet so, but I'm not unfortunately 🙂

so, without having the actual math handy, you'd still do essentially the same thing, apply the camera projection matrix to each of the endpoints of d, the distance between those two points is the projected width d' in view coordinates, and from that you calculate the FOV. this way you don't actually need to know the weird center distance to d, instead just use the endpoints

indigo spoke
compact ingot
#

how do you know how big d is?

indigo spoke
compact ingot
#

ic

#

there should be a simple formula for that

#

feels like it

indigo spoke
#

That's been my struggle 😄 Looks simple but can't get it right

#

Anyhow, thanks for all the help, need to catch some zzz's 🙂

compact ingot
hearty beacon
#

I'm having a super weird issue.

In my scene, I have a BeatManager script, which listens to multiple BeatCounter scripts. They essentially determine when a beat happens in a song, then pipe that data to the BeatManager. BeatManager then sends out that beat information to any object that subscribes.

When I reload my scene, the BeatCounters stop sending out beat signals.

BeatCounter: https://paste.ofcode.org/39VyytuyRDvz7qKwtFCCzWX

BeatManager: https://paste.ofcode.org/DSJRWQLQpTF8ByUy8VSEJg

Wouldn't reloading the scene completely refresh these objects? They work if I LoadScene without having had the scene loaded prior, so that's what is confusing me.

orchid marsh
#

How to post !code

thorn flintBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

orchid marsh
#

Otherwise, loading the scene from another and reloading itself should produce the same results.

hearty beacon
#

I can navigate to it from the menu screen and it works fine, using SceneManager.LoadScene("Level")

But if I am in the scene and navigate back to the main menu, then into the scene, or back into the scene (with a restart function that just reloads the scene) in the same instance of the game running, it no longer works.

#

So visiting the scene at all means it won't work if revisited at all in the same instance of the game running

orchid marsh
#

Do you've got any dependency with non destroying objects?

#

DDOL, static etc

hearty beacon
#

The only non-destructive object is the game manager, which only stores things like overall volumes and settings

#

Wait...

orchid marsh
#

What about this Beat Manager?

hearty beacon
#
public class BeatSynchronizer : MonoBehaviour {

    public float bpm = 120f;        // Tempo in beats per minute of the audio clip.
    public float startDelay = 1f;    // Number of seconds to delay the start of audio playback.
    public delegate void AudioStartAction(double syncTime);
    public static event AudioStartAction OnAudioStart;
    
    
    void Start() {
        double initTime = AudioSettings.dspTime;
        GetComponent<AudioSource>().PlayScheduled(initTime + startDelay);
        if (OnAudioStart != null) {
            OnAudioStart(initTime + startDelay);
        }
    }

}```
#

This might be throwing it off

#

That static event

#

I changed it to a public nonstatic event and made the object a singleton to reference it that way so it would get reloaded on the scene reset, but that didn't seem to fix it

hearty beacon
#

The BeatCheck coroutine in the BeatCounter script

orchid marsh
#

Place a log and see if it's running after beat no longer works.

hearty beacon
#

Tried, it isn't

orchid marsh
#

Within the coroutine, not the Beat event.

hearty beacon
#

I've done both

orchid marsh
#

If the coroutine loop was false, it'd terminate.

hearty beacon
#

Oh wait, I see what you measn

#

Hang on

orchid marsh
#

So it's terminated.

#

The loop failed.

#

Determine why it was false: while (audioSource.isPlaying)

hearty beacon
#

I think I might be the dumbest person on the planet. I set timescale to 0 on gameover and never set it back after reset or main menu, so that's why it wasn't working.

Literally can't believe I did that.

#

I think for whatever reason I told myself that reloading the scene also reset timescale, which obviously is not the case lol

calm ocean
#

I currently have an Editor that uses [InitializeOnLoad] to listen to SceneView.duringSceneGui. However, I only want it to listen when there is a particular component in the scene. I found that FindObjectOfType to see if that component exists works, and I don't think it's that much of a performance hit, but I was wondering if there is a better way to go about this.

I tried hooking the editor up to that component through [CustomEditor(...)], but the thing listens even when the scene does not have that component.

tropic vigil
calm ocean
tropic vigil
calm ocean
#

I see, so the key insight is that the component can add itself to a list somewhere that the editor can also access. Thanks.

hexed meteor
#

Anyone know if its possible to add a reference to a class to a scriptable object? If I want to dynamically add or remove a component, and for the scriptable object to determine that component, is this possible?

#

could I potentially just use a string with the class's name?

proper walrus
#

would anyone know how to resolve this problem concerning horizontal layout group and child expansion? https://gamedev.stackexchange.com/questions/205527/unity-how-to-expand-a-child-in-a-horizontal-layout-group-to-the-left

dusty wigeon
#

Alternatively, you can use Prefab if it makes sense in your use case.

dusty wigeon
proper walrus
sharp pine
#

hello guys

#

i have a problem with Vector3.SmoothDamp, can someone help me out?

sharp pine
#

I have an IEnumerator that sets the position and the rotation of a gameobject with Vector3.SmoothDamp() and Slerp(). But somehow the gameobject stops midway and also the rotation has not finished. I have tried changing the loop to while(true), and it works, but this wouldnt complete the process in the time that is given in movementTime.

Here is my code

```IEnumerator ToPerspective(Vector3 position, Quaternion rotation)
{
    float elapsedTime = 0;
    camIsMoving = true;
    desiredPosition = position;

    while (elapsedTime < movementTime)
    {
        elapsedTime += Time.deltaTime;
        transform.SetPositionAndRotation(Vector3.SmoothDamp(transform.position, position, ref currentVelocity, movementTime), Quaternion.Slerp(transform.rotation, rotation, movementTime * Time.deltaTime));
        yield return null;
    }
}```
thorn flintBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

sharp pine
empty shell
# sharp pine I have an IEnumerator that sets the position and the rotation of a gameobject wi...

I will try to help with what you give here.

I don't know much about SmoothDamp, but for Slerp, I got a lot of problems doing movementTime * Time.deltaTime.

Sometimes, I had the object flickering and did not do what we designed it for. I prefer to use a Smoothstep function. If you want to learn more about the subject, I suggest you look here: https://www.youtube.com/watch?v=mr5xkf6zSzk.

I can't help you more than that.

#

Here is a problem I have:

Does anyone would know if it's actually possible to make an animation work while loading a scene even if the loading of the scene would take longer?

I got something I want to show the player before the game starts, like the first Angry Birds game: https://www.youtube.com/watch?v=aiiQ8btusrs&t=22s

I tried to use LoadSceneAsync(sceneID, LoadSceneMode.Additive), but it almost completely shuts down whatever was happening in the previously loaded scenes.

Here is what I got on the scene management side of things:

private IEnumerator LoadScene(int sceneID)
    {
        AsyncOperation asyncOperation = SceneManager.LoadSceneAsync(sceneID, LoadSceneMode.Additive);
        CanSwitchScene = false;
        while (!asyncOperation.isDone)
        {
            //Do something each frame, but almost it's not smooth at all.
            yield return null;
        }
            
        CanSwitchScene = true;
    }
proud cipher
empty shell
#

What I did was that the current scene that had the animation is the menu scene.

#

It just pauses right after a canvas appears

#

When the scene I aim to go to is loaded, the animation can occure.

flint geyser
#

Why does my IJobParallelFor gets paralleled only to 2 threads?

private struct FindNearestFoodJob : IJobParallelFor {
        [ReadOnly] private readonly NativeArray<Vector3> _foodPositions;
        [ReadOnly] private readonly NativeArray<Vector3> _headPositions;
        [NativeDisableParallelForRestriction] private NativeArray<Vector3> _results;

        public FindNearestFoodJob(NativeArray<Vector3> foodPositions, NativeArray<Vector3> headPositions, NativeArray<Vector3> results) {
            _foodPositions = foodPositions;
            _headPositions = headPositions;
            _results = results;
        }

        public void Execute(int index) {
            float sqr = float.MaxValue;
            foreach (var foodPosition in _foodPositions)
            {
                float distSqr = (foodPosition - _headPositions[index]).sqrMagnitude;
                if (distSqr < sqr)
                {
                    sqr = distSqr;
                    _results[index] = foodPosition;
                }
            }
        }
    }```
sage radish
flint geyser
#

Entire method of setting them up?

sage radish
flint geyser
#
_jobHandle = job.Schedule(botsCount, 32);```
sage radish
flint geyser
#

40

sage radish
# flint geyser 40

That explains it. The 32 is the innerloop batch count. It's how many iterations each thread should do. So one thread is doing 32 iterations and the second thread is doing the rest, 8.

flint geyser
#

Let me try to change it

#

To, say, 1

sage radish
#

You could set it to 1 to map each index to its own thread, but there's an overhead to starting a thread (also most CPUs don't have 40 logical cores, so some threads will have to wait anyway).

#

You'll need to use some trial and error to find the right balance for your particular case.

flint geyser
#

Is it fine to not use powers of 2?

sage radish
#

The relevant section here:

Batch size should generally be chosen depending on the amount of work performed in the job. A simple job, for example adding a couple of Vector3 to each other should probably have a batch size of 32 to 128. However if the work performed is very expensive then it is best to use a small batch size, for expensive work a batch size of 1 is totally fine. IJobParallelFor performs work stealing using atomic operations. Batch sizes can be small but they are not for free.

proud cipher
flint geyser
#

My job is pretty simple but the calculations inside are performed 40000 times...

sage radish
flint geyser
#

I mean 1000 iterations of the loop for each bot

#

And there are 40 bots

proud cipher
#

Can’t be needed

heavy rune
#

i have a script where a gameobjects moves left, for some reason, in playtime its position only changes between x(482.0) and x(482.1). no other positions, even though im telling the object to move left. Whats causing it to not advance?

proud cipher
#

What’s the code

heavy rune
#

rb.velocity = new Vector3(5, 0, 0);

proud cipher
#

Is that in update

heavy rune
#

yes

#

the issue is not the code

#

its something in the editor

proud cipher
#

Is there anything else controlling the movement in code

heavy rune
#

no

proud cipher
#

What about the editor? Also it’s better to use xF floats for velocity and positions

heavy rune
proud cipher
proud cipher
#

Have you enabled movement constraints in the rb

proud cipher
#

Is the rb the correct rb

heavy rune
#

yes its correct

proud cipher
#

Is this in runtime ?

heavy rune
#

yes

proud cipher
#

Why are you trying to move it in runtime

heavy rune
#

because it doesnt move by code either

proud cipher
#

Doesn’t make sense to me

heavy rune
#

is this a glitch?

proud cipher
#

Maybe an animation is keeping its position there

#

If you have looping idle

heavy rune
#

i turned off everything exept the code which only contains "rb.velocity = new Vector3(5, 0, 0);"

proud cipher
#

Show script

dusty wigeon
#

Do you have any collider that could interfere with the movement of your object ?

heavy rune
proud cipher
#

@heavy rune are you trying to move the object via scene view instead of game view + are you selecting move and not just click

proud cipher
heavy rune
#

yes

proud cipher
#

Are there any errors or warnings

heavy rune
#

no

dusty wigeon
#

Make an empty scene with this in it.

proud cipher
#

It should be working if you haven’t disabled something

heavy rune
#

rn i realised what was making it stuck - the animator which wasnt even activated

proud cipher
#

I said the animation may be

heavy rune
proud cipher
#

New state 0 could be infinite loop of default position

#

It needs to have connections between the animations to switch

timber flame
#

What is the most common way to implement and get coastlines in voxel based games? I mean edges of an island
Marching cubes?
two-pass algorithm with perline?

flint geyser
#

I have 40 worms, each with a head, about 30 body parts and a tail. All these 32 parts have a rigidbody and a collider. 40*32 = 1280 pairs of rigidbodies and colliders and I move and rotate each of them every frame. Performance with this setup is very poor, about 30FPS on a good PC, but the game is supposed to be for Android. The reason for having colliders on each part is to let bots check if there is any worm around with Physics.OverlapSphereNonAlloc and flee if it's the case. The reason for each of them is that it appeared to me like it was way more expensive to move a collider without a Rigidbody than a Rigidbody with a collider. Could you recommend any kind of optimisation to me? I can think of only one, a hellish one, - to store the position of each body part as Vector3 and go over all of them checking for distance without physics. Given that I can parallel it to jobs and use Burst for that sounds like several times more FPS to me.

timber flame
flint geyser
#

It is written in the same message, isn't it?

compact ingot
plush hare
#

you can also uncheck "enable enhanced determinism"

#

other settings like that can improve performance.

compact ingot
#

those wont make it run on mobile

plush hare
#

that's why I said to lower the timestep

#

which you disagree with

compact ingot
#

yes its useless

#

its a fundamentally wrong way to do this

plush hare
#

How is it fundamentally wrong?

#

The default timestep at 50hz is too high for shitty mobile devices

#

30hz and interpolation is completely fine

flint geyser
#

Anyway I don't see how lowering the timestep improves the situation, it only makes worse, beause the code is performed in FixedUpdate

plush hare
#

that doesnt make any sense chief

flint geyser
#

Okay it makes sense if FPS is very low

#

But I want my FPS to be HIGHER than 30

plush hare
#

no shit

compact ingot
#

you need to find a way to simulate your worms without rigidbodies and collision callbacks

#

probably a semi-custom simulation and clever overlap checks that dont happen each update

flint geyser
plush hare
#

running your physics simulation at 30hz != running your game's visual render at 30hz

#

decreasing the physics timestep WILL increase performance

#

it's a fact.

compact ingot
#

you don't want to 2x the performance here by tweaking the physics time step, you want to 10x or 100x it by using a fundamentally better architecture

flint geyser
#

Pretty much every 1/30ms there will be a huge lag. Ultimately 30fps if not worse experience because of constant change in framerate

plush hare
#

You understand that cod warzone simulates at 10hz right?

flint geyser
#

No I don't

#

No idea about it

#

I tell you what. If it takes 40-50ms on PC and it is not the limit how much will it be on phone? 150ms? Way more. But let's take 150ms. Even if I run it at 10hz, FPS won't be adequate. Am I not right?

sage radish
# plush hare 30hz and interpolation is completely fine

If the physics update is too expensive to run (which in this case it is), then it's not a huge improvement if that update is called less frequently. It just means that instead of every frame taking too long, it's every other frame, or every 3rd frame, etc... From an average FPS stand point, yes it improves, but the minimum FPS will remain unchanged and it will feel stuttery.

compact ingot
#

optimizing a fundamentally flawed approach is a waste of time

sage radish
#

But one thing you can do is move some other computations to just the frames where there isn't a physics update. It's just tricky to balance that so you end up with a smooth FPS.

plush hare
#

Sorry, but you're not optimizing Physics.Overlap

#

I don't know what you all are trying to argue here

compact ingot
#

we are just frustrated by the discussion that entirely misses the core of the problem

plush hare
#

What is the core problem? That physx simulations run like ass on mobile devices?

compact ingot
#

that you don't even need physics simulation

plush hare
#

True

dusty wigeon
sage radish
#

I think a Bursted Job combined with a good spatial tree can go a long way here.

compact ingot
#

the performance problem rn isn't even the overlap, its the N:N collisions between 1280 objects

flint geyser
#

Actually Overlap takes about ten times less time than Physics.UpdateBodies and Physics.Processing combined

compact ingot
#

just delete the rigidbodies, seriously

flint geyser
#

And leave the colliders? Than it will perform worse, tested

sage radish
#

Moving static colliders has additional cost in PhysX, since it's probably recreating some spatial tree.

plush hare
#

Even if we get rid of the rigidbodies, you should still absolutely find a way to separate the simulation logic from the rendering

#

ensure that you aren't doing your overlap checks in Update()

flint geyser
#

It isn't

#

It is in FixedUpdate

sage radish
flint geyser
#

So what do you think of the approach?

#

Not too wild?

sage radish
# flint geyser Not too wild?

If you're using sphere colliders for all the parts, then it simplifies the problem to just a bunch of distance checks between points. Putting those into an octree and reading from that doesn't sound wild to me, but maybe someone has a different approach.

flint geyser
#

Good, not sure about the tree tho, never used anything like that

#

It talks about some raycasts and AABBs, is it even what I need?

sage radish
#

Doing it brute force with 40*32 parts would be 1,638,400 comparisons. Maybe that's low enough to not warrant an octree, but it doesn't scale well.

compact ingot
#

are your colliders triggers and are they colliding with each other?

#

i.e. does the physics layer collide with itself?

flint geyser
#

Yes and yes

#

But why would it...

compact ingot
#

if you remove the self collision and rigidbodies you can move thousands of triggers each update without issue

#

and you can still detect them via overlap queries and a layer mask

flint geyser
#

Oh, it doesn't

#

Good from me

flint geyser
compact ingot
#

then if you reduce the count of the triggers, mayb only on the head and tail or ever n-th bodypart, you can cut it down further

#

for proximity checks triggering a flee behaviour its probably sufficient to have 1 or 2 sphere or capsule colliders that approximate the worm shape, since you dont need precise collisions

sage radish
compact ingot
#

and once you are down to 40 colliders, you could just ditch all of them and do what stable said and run down a list you calculate each frame

flint geyser
#

I am not getting what you are saying Anikki

sage radish
flint geyser
#

Oh now I get it

#

Tho this suggestion implies pretty noticeable mismeasurements of shape, so I don't like it

#

It could be fine for flee behaviour, but I am also supposed to die when I bump into any of them

compact ingot
#

you could tile your play area into a static grid, sized to approximate the flee distance of the worms, each update have each bodypart figure out which grid cell it is in, if the cell is already occupied by another worm, flee, if not then write its ID into that grid cell. you can improve this with a tree (octree etc.) or you could do the same thing with the triggers from the physics engine which maintains a BVH

flint geyser
#

Exactly

flint geyser
#

Don't know why I didn't think about it

#

🙂

sage radish
flint geyser
#

I don't mind a bit more memory actually

sage radish
#

For a large map like in slither.io, it might not go well. Square law and everything

compact ingot
#

also depends on how coarse the grid is

#

and whether its even a grid or just a hashset

flint geyser
#

By my calculations it shouldn't take up more than 1MB

#

What do you think?

compact ingot
#

the idea is basically to have static cells of some kind and no movable triggers on your agents, and use a kind of 1-pass bucket sort

flint geyser
#

Also my map will finally become more scalable

#

I think there isn't anything else to discuss on this topic, what do you think?

compact ingot
#

everything was said 😄

sage radish
#

</discussion>

flint geyser
#

Thanks, bye

dapper cave
#

possible regression: who else found that 2022.2.18 is 10x slower than 2021.lts at asyncgpu readback?

sand acorn
#

Hello there, I am currently making a 2D experiment, I want to subdivide a polygon collider so a simple sprite (cube sprite) can have more places to deform from, how can I do this? I have a script that lets me deform the terrain using the mouse but it doesnt(subtract the terrain but rather creates collider points on the mouse position

static igloo
dusty wigeon
dusty wigeon
little trench
#

Is it possible to self-sign a windows .exe, or do you have to spend money to buy a signing cert from a CA?

static igloo
dusty wigeon
static igloo
#

How does saving have anything to do with my game?

rugged river
#

Hello. I am not sure if this is the right channel for this question, but I am researching options to do streaming unity to a browser and possibly wearables. I would want to do all the rendering on a server and then have it streamed to a device or browser (edge devices) which may have low gpu/cpu hardware. In my Unity app, I have several models, each in their own scene. I would want a user to be able to go to a URL and load the scene in their browser. I would have simple inputs as well, on the device side, to interact with the unity scene. But, each user who view a particular scene should have their own session(or an option to join a session already in process). From what I was reading, it looks like Azure Remote Modeling is the way to go here? I also did a quick demo using Unity Render Streaming. But, what I noticed is that there seemed to be one session. I.e, I would run Unity on my computer and all browsers that were receiving the broadcast would all see the same thing. for example, if a user in one browser moved their camera, everyone's camera moved.

tropic stag
#

I have a system where particle systems have "mirrors", basically another instance of the same prefab but with an offset position. Is there a way to "instance" unity's particle systems to automate any changes to all the mirrors (changing particle start color and stopping them). Is there a method that would have any performance benefits over just keeping a list of the mirror objects in csharp and looping over them so all are stopped or change color at the same time?

dusty wigeon
tropic stag
dusty wigeon
tropic stag
dusty wigeon
# tropic stag yeah, I was thinking there's a way to basically say "render this particle system...

No, there is no way to directly that. They may be some way of doing so by using a Command buffer, but it might requires to make a Custom Scriptable Pipeline to achieve good results. (https://docs.unity3d.com/ScriptReference/Rendering.CommandBuffer.DrawRenderer.html, https://docs.unity3d.com/Manual/srp-custom.html)

Anyway, you should not try to do that. Find an alternative and focus on what really matters. The best advice I can give you is: Work with the tool you have, you are doing a video game not an engine.

stuck onyx
#

Do I need a custom plugin to write in the logs of the OS ? I understand Debug.Log. just works when working on debug or connected directly to xCode, but I want to log stuff of my game in the iOS logs so i can retreive them later?

dusty wigeon
stuck onyx
#

theoretically to write the logs in iOS you gotta use NSLog

#

but thats native i cannot access that without a plugin

#

didn't find one though

sly grove
#

Can't you just use the normal File API?

stuck onyx
#

uhmmmm, i guess i could...

sly grove
#

or use any existing C# logging framework?

stuck onyx
#

yeah ill do that

#

forget it

#

any recommendable one ?

#

i used Log4 something in the past

#

dont remember the name very well

sly grove
#

I used to use Log4J as a Java developer

#

idk what the C# equivalents are

stuck onyx
#

thanks @sly grove

#

ah, it was Log4Net

hushed fable
stuck onyx
#

thanks

compact ingot
#

!collab

thorn flintBOT
dusty wigeon
sly grove
dusty wigeon
sly grove
#

I believe you, not really in a position to test it at the moment

rugged river
dapper cave
static igloo
#

🤔

fathom abyss
#

Hello everyone. I'm trying to make a pathfinding algorithm, but nothing comes to mind at all. Can you tell me in which direction it is worth thinking?

Initial conditions: some adjacent rectangles. There is a start point in the first, and an end point in the last. It is necessary to find the path with the least number of turns through the edges of the intersection of rectangles.

Known :
coordinates of the corners of rectangles
coordinates of the beginning and end of the intersection edges
coordinates of the beginning and end of the path

The approximate result is shown in blue on this illustration

The main point of the question: the part about the least of turns)

sage bolt
#

is it possible for there to be two paths through the level? and does length matter at all?

fathom abyss
sage bolt
#

good to know. especially the ordered edges

#

my first throught would be to get a range of lines that go from start to the first edge

#

from there see if there is a line within those parameters that goes through the next edge

#

continue until no more edges can be passed through using those parameters

fathom abyss
#

I think to simplify for a start, let there always be exactly 3 rectangles here

sage bolt
#

in a three rectangle example theres either one line through all, or not

#

so check for that first

#

one other question, do the walls have size or are they just data

#

if they have no size then this should be a valid path for example

dusty wigeon
tropic vigil
#

Also it gets more messy if the walls have width. 🤔

fathom abyss
# sage bolt continue until no more edges can be passed through using those parameters

Yes, that's about what I was thinking, but before reducing the number of rectangles, my thoughts run away.

Then I'll try something like this:

line right to the end and check the previous edges. If it didn't work out - line to the next one edge from the end and repeat. Checks 3 times for every edge: the beginning, middle and end of each. If it didn't work out even for 2 in a row, then try to achieve the next rectangle in the centers of the conditional quarters and repeat the procedure from each. Maybe there is some kind of mathematical equation here, how to quickly check it with coordinates alone, but this is definitely not for me.

sage bolt
#

not doing it with math and equations it will be very difficult to find the lowest number of turns

dusty wigeon
#

You could also start with a valid path, and try to reduce the amount of turn.

sage bolt
# tropic vigil I think I would start with casting a line from the start to the edges of "doors"...

building of this solution, you could go from start throughout the maze recursively. should scale with large mazes?
get the total area in the next rectangle that a line from start could hit. if that area has another shared edge, then get the area from start to those edges instead.
from that area, get the area it could cast into the next rectangle. if it hits another shared edge, get the area it could cast into that rectangle.
repeat until end is in your area

fathom abyss
tropic vigil
#

If we start going for door edges recursively, we will end up with some decent solutions, but not every possible solution will be found. In the illustration we can see that starting doing it from the left we will end up 4-line solution (first blue, then red, then we won't reach the blue, so we will need 2 extra lines instead), while starting from the end we will end up with better solution (blue, green and blue again)

fathom abyss
sage bolt
#

if edges dont have thickness you can also cast directly from that bottom left corner

#

would casts from all 4 corners through both edges of the shared side be optimal?

#

actually the whole box should be reachable in 1 turn assuming no edge width

tropic vigil
#

The perfect solution has a point anywhere in the yellow area (assuming the walls don't have thickness).

sage bolt
#

true

#

im just thinking in bigger examples you would need some kind of way to recursively go on one direction

#

although all i gave was the area reachable not the optimal solution

tropic vigil
sage bolt
sage bolt
tropic vigil
#

If every ray would result in another 2 rays, then the complexity is 2^n. On the other hand, if we did it from both sides, then there would be a need for search intersections. Multiplying each ray by each ray would return us to the complexity 2^n once again. 🤔

Gonna be honest: I think I would need to spend at least a day thinking about edge cases before finding a good solution. 🤷‍♂️

sage bolt
#

oh wait intersections

#

nvm

fathom abyss
#

Thank you all very much, you had a very interesting discussion. But since my brain is already melting (It's after midnight here), I'll start with a simplified solution In 3 rectangles.

  • First try one straight line start-end,
  • If it doesn't work out, then the oncoming caste and the intersection zone
  • if there is no intersection, then any point of middle rectangle, the second edge and to the end.

And depending on my free time, I will already expand for a potentially endless maze)

urban warren
#

I have a graph structure, where each node is serialized to its own file, and has a list of child IDs and a parent ID.
This only has one issue, since each node is its own file. When working with a VCS, one node file can be pushed, but not the others, which can result in issues.
For example, add a child to a node, but only push the parent node. Now it has a dangling child ID.

My thinking was to instead, only keep a parent ID, and add the children on load. But the issue with that is how to keep them ordered. I could store an int with the nodes index relative to its siblings. But that gets messy if you start to add/move/remove some nodes.

Any ideas, or questions?

south mason
#

I'm creating a loading screen and I want to create a UI menu at runtime that shows metadata for each file. What's the best way to build UI that can accomplish this?

#

I feel I need to make some sort of UI template and then create a menu procedurally that populates each item from the template and puts them on screen somehow

thin mesa
#
  1. this is a code channel
  2. this is not advanced
  3. restart the editor
keen zinc
#

sry i thought i was in general

dusty wigeon
urban warren
# dusty wigeon I have 0 idea of what you are talking about, but usually for circular reference ...

I have a class like this. I do two pass when loading the nodes. Once to load them and put them in a Dictionary<Guid, Node>, and a second pass to assign the references to the nodes uses the parent and child ids that are stored.

public class Node 
{
internal List<Guid> ChildrenIDs; // Serialized to file.
internal Guid ParentID; // Serialized to file.

public Guid Id; // Serialized to file.
public List<Node> Children; // Not serialized to file
public Node Parent; // Not serialized to file
}
#

The issue is that if I have NodeA and add a child NodeB to it. But only push NodeA to the VCS, NodeA will have a id in the ChildrenIDs list that goes to no node because NodeB was not pushed.

sage radish
#

You're always going to have potential issues if it's possible to forget to push individual nodes. Like if Unity saved scenes by storing a file for each GameObject.

urban warren
#

(This is for my asset that lets you create collections of Assets)

sage radish
#

So what are you hoping to improve? Obviously, if some node isn't pushed, then it isn't pushed and can't be part of the graph. So are you trying to find the most graceful way to fail?

urban warren
#

Well, for example if I only keep the ParentID, then it won't have any issues if a child is not pushed. Each node would be fully self contained so to speak.

#

If a child node is pushed without the parent, it can fail gracefully by simply adding it to the root node instead

sage radish
#

But wouldn't it be better to fail loudly by saying "Hey, this node is missing some children!" rather than fail silently?

urban warren
#

Nah, some people are adding nodes only locally, or forget to push the parent or child change. And at that point it is already to late to fix it nicely

#

The only issue with the ParentID approach is that it doesn't keep the order of the nodes.

sage radish
#

In my mind, I'm comparing this to as if I push some change to a scene where I add a prefab, but I forgot to push the prefab with it. When a teammate pulls that scene change, they'll have a red item in the Hierarchy saying "Missing Prefab". They can let me know, and then I push the prefab and problem fixed.

#

Does that not apply here?

urban warren
#

Actually, that might work you're right

#

I will try that (might be something I am forgetting about), thanks! 😄

tawdry lintel
#

If anyones familiar with Facepunch Steamworks:

I setup a lobby on one client, and then when the other tries to join it goes through
SteamFriends.OnGameLobbyJoinRequested += (lobby, id) => { JoinLobby(id); };

but the lobby isnt right? The id doesnt match the one created, and all the data isnt right. Max players is 0, the SetData() I set isnt there, etc.

gleaming sail
#

Is there a way to do procedural cubemaps? Like if I wanted to generate my own in shader graph or code?

#

Every search comes up empty

jaunty leaf
#

@tawdry lintel I have no idea about that api sorry but sounds like the data your getting is the type defaults, are there serialisation settings and hooks you can use to debug?

tawdry lintel
pastel wagon
#

does static batching do emissive/specular in a separate pass that doesn't include batching? I'm seeing something kind of weird where certain meshes seem to get drawn twice - once as part of the large static batch and then again individually, and it only seems to kind of "brighten" the object. Is this expected?

bleak citrus
#

pretty sure static batching just welds meshes together

pastel wagon
#

Yes. What I’m seeing is one draw call with stuff welded together, and then N draw calls later where they’re each drawn individually. The later pass is just “brightening the image so I’m wondering if that’s just specular, and whether that behavior is expected

dusty wigeon
sage radish
#

The meshes are combined, but they are still separate draw calls, but even the official documentation contradicts itself in the first paragraph.

Static batching is a draw call batching method that combines meshes that don’t move to reduce draw calls. It transforms the combined meshes into world space and builds one shared vertex and index buffer for them. Then, for visible meshes, Unity performs a series of simple draw calls, with almost no state changes between each one. Static batching doesn’t reduce the number of draw calls, but instead reduces the number of render state changes between them.

pastel wagon
#

again...I'm seeing each object being rendered in two passes. In the first pass the entire batch is rendered as a single mesh and draw call. In the later pass each object is rendered in its own draw call, and the only effect on the framebuffer is to "brighten" it. So I'm wondering if:
A) is this a specular pass?
B) is this expected?
C) is there anything I can/should do about it?

dusty wigeon
dusty wigeon
#

Unfortunately, I have little to no knowledge about the inner working of the lighting system of Unity as we use our own. That being said, we have specific draw call for things like shadow as we "fake" them.

#

That being said, do you have any issue in term of performance ?

pastel wagon
#

I mean, performance can always be better…works fine enough in simple scenes but heavier stuff gets bad. I’ve already cut off a ms of rendering time with static batching.

I might experiment with manually combining the meshes because then it should be impossible for it to not be drawn in one call…

dusty wigeon
#

There is so much things that can be improved.

#

What is your target platform and what is your number of Draw Calls and Triangles ?

pastel wagon
#

windows

#

this is actually a pretty simple test case

#

draw calls was ~7500 before batching (same tris/verts)

#

I was actually hoping that the batching would improve main thread CPU perf, but it seems like it mainly affected the gpu/render thread

dusty wigeon
# pastel wagon windows

There is something wrong here. 6000 Draw Calls for 1.4M Triangle is not what I would expect

#

Also, note that 6000 Draw Calls is way higher than what you should aim.

pastel wagon
#

heh. well I'm working on a mod, so I have limited ability to make big changes. And there are a large number of small, simple meshes...which is why I'm trying to use batching

#

6k draw calls for 1.4M triangles is high?

#

maybe this is a good palce to ask...this is for a cockpit mod for kerbal space program, so there are a lot of switches, indicator lights, etc that can all move or be colored independently. Currently those are each their own draw call, and I'm trying to batch the static parts of those objects together (things that use the same material and never move). Is there a better way? Skinning maybe?

dusty wigeon
#

You number of triangles is pretty low. The issue is the amount of object batched.

If there is a lot of repetition, you should look into Instancing.

#

Also, you could probably activate Dynamic Batching.

#

If you are not in HDRP.

pastel wagon
#

Does dynamic batching have a high cpu cost? I’d be surprised if not based on the docs…

dusty wigeon
sage radish
#

I cannot speak for the Static Batching

sand acorn
lime stream
#

Is there a function from the NetworkManager that checks when a new client has connected, there is a ConnectionApproval but I can't seem to figure out how it works and the documentation for NGO's latest version is not so thorough or explains it well, I am trying to make a lobby that has 4 player cards and when three clients join they are assigned a position as they join, but if a player (host) joins first they get a 4th spot which is reserved, can I use clientId or so to differentiate.

I have this simple player script that gives each player a P1-P3 when spawning but if I wanted to do the same thing on the lobby without spawning players yet and show it on the UI how can I do it, and how can differentiate the clients vs the host (The host will be the special slot)?

    public override void OnNetworkSpawn()
    {
        networkPlrName.Value = "P" + (OwnerClientId + 1);
        plrName.text = networkPlrName.Value.ToString();
    }
devout coyote
#

Reminder that all the code will be executed on all sides

#

So same for host and client

#

If you are using unity's lobby system there will be dedicated methods for listening to new connections

#

The host always joins first by the way, how else would a lobby be started?

lime stream
devout coyote
#

IsHost and IsServer then

#

And OnClientConnected

#

Be aware that sometimes in awake / start these are always false

#

OnNetworkSpawn is the safest place to check whether host or client

lime stream
#

I do have a script that uses OnNetworkSpawn that changed the player's name and sprite based on this but it does not seem to work

#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Unity.Collections;
using Unity.Netcode;
using TMPro;

public class PlrSettings : NetworkBehaviour
{
    [SerializeField] private TextMeshProUGUI plrName;
    [SerializeField] private SpriteRenderer plrCurrentSprite;
    [SerializeField] private Sprite[] plrSprites;
    [SerializeField] private NetworkVariable<FixedString128Bytes> networkPlrName = new NetworkVariable<FixedString128Bytes>("", NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Server);

    public override void OnNetworkSpawn()
    {
        if (NetworkManager.Singleton.IsClient)
        {
            networkPlrName.Value = "P" + (OwnerClientId + 1);
            plrName.text = networkPlrName.Value.ToString();

            if (OwnerClientId + 1 == 2)
            {
                plrCurrentSprite.sprite = plrSprites[0];
            }

            if (OwnerClientId + 1 == 3)
            {
                plrCurrentSprite.sprite = plrSprites[1];
            }
        }

        if (NetworkManager.Singleton.IsHost)
        {
            networkPlrName.Value = "DM";
            plrName.text = networkPlrName.Value.ToString();

            //Change DM sprite
            plrCurrentSprite.sprite = plrSprites[2];        
        }
    }

}
#

Client on left and host on the right

humble walrus
#

I'm looking to make a game in which players can drag and drop components onto a player-character, essencially a "shipbuilding" style game, but where the ship in question is a swordsman, ect, ect.

Is there a way to create new prefab assets using in-game code rather than the editor, in such a way that I could create a drag and drop system, take all the items in it, and then turn them into a prefab that could later be instantiated?

I've been looking into other ways to handle it, like making a list that tracks every value of every item, and instantiating all of its individual parts as needed, but if there's a way to save and load to prefab assets, it would certainly make things a lot easier.

I've seen that there's a method to save things as prefab assets, but I'm uncertain if it functions in a built game, as it uses UnityEditor.

#

Essencially, I'm looking into seeing if there are ways to save/load assortments of objects that have complex position, rotation, parentage, and so on, in a clean way.

dusty wigeon
humble walrus
#

Darn, so in short, I'll have to set up a system to record parents, locations, rotations, and other variables and a way to instantiate them all as needed.

dusty wigeon
flint geyser
#

How to test for collision detection in 3d using boxes (not spheres) when the boxes aren't axis aligned? (without using Unity's physics)

compact ingot
compact ingot
# flint geyser WITHOUT using Physics

do something like this for all corners ```cs
bool OverlapBox(Vector3 point, Bounds box, Quaternion orientation)
{
Vector3 max = orientation * box.extents+ box.center;
Vector3 min = orientation * -box.extents + box.center;
Plane left = new Plane(orientation * Vector3.left, min);
Plane right = new Plane(orientation * Vector3.right, max);
Plane up = new Plane(orientation * Vector3.up, max);
Plane down = new Plane(orientation * Vector3.down, min);
Plane forward = new Plane(orientation * Vector3.forward, max);
Plane back = new Plane(orientation * Vector3.back, min);
bool isOutside = left.GetSide(point) || right.GetSide(point) || up.GetSide(point) || down.GetSide(point) || forward.GetSide(point) || back.GetSide(point);
return !isOutside;
}

sly grove
flint geyser
#

But what is a Plane in this context?

compact ingot
#

the planes defined by the sides of the cube

#

a box check is made by making 6 plane-side-checks against a point

flint geyser
#

Could you possibly teach me how you got this code or provide me with a few other things on this topic? I also need to know how to detect collision between a sphere and a box and insides of the Plane

compact ingot
#

if you want to know it two boxes intersect you can simply check if any corner point is inside the other box

flint geyser
#

Oh(

#

I imagine I could check whether a side of the cube is between the cube's center and the (sphere's center + sphere's radius)

#

Correct?

compact ingot
# flint geyser Correct?

yes, just add a range check to the point-check above, this code can probably be optimized significantly

        bool OverlapBoxAndSphere(Vector3 sphereCenter, float sphereRadius, Bounds box, Quaternion orientation)
        {
            Vector3 max = orientation * box.extents + box.center;
            Vector3 min = orientation * -box.extents + box.center;
            Plane left = new Plane(orientation * Vector3.left, min);
            Plane right = new Plane(orientation * Vector3.right, max);
            Plane up = new Plane(orientation * Vector3.up, max);
            Plane down = new Plane(orientation * Vector3.down, min);
            Plane forward = new Plane(orientation * Vector3.forward, max);
            Plane back = new Plane(orientation * Vector3.back, min);
            bool isOutside = left.GetSide(sphereCenter) && left.GetDistanceToPoint(sphereCenter) > sphereRadius 
                || right.GetSide(sphereCenter) && right.GetDistanceToPoint(sphereCenter) > sphereRadius 
                || up.GetSide(sphereCenter) && up.GetDistanceToPoint(sphereCenter) > sphereRadius 
                || down.GetSide(sphereCenter) && down.GetDistanceToPoint(sphereCenter) > sphereRadius 
                || forward.GetSide(sphereCenter) && forward.GetDistanceToPoint(sphereCenter) > sphereRadius 
                || back.GetSide(sphereCenter) && back.GetDistanceToPoint(sphereCenter) > sphereRadius ;
            return !isOutside;
        }
flint geyser
#

Thank you very much

plucky laurel
#

nah its rayOOBintersect

#

do you really need 6 planes? why not 3?

#

trying to picture if its possible even

flint geyser
#

why 3?

plucky laurel
#

to save on computations for each cube face

flint geyser
#

I mean how

plucky laurel
#

if it would be possible to get side, offset by normal a point..

#

probably not

#

but you probably can early exit if you do sqrmag comparison with max length inside box vs total

flint geyser
#

Wait this method doesn't account for world position does it?

plucky laurel
#

seems to account, sphereCenter and Bounds has center

flint geyser
#

But Bounds don't account for world position

plucky laurel
#

they do

#

bounds is just a min max

#

you can use it in any space

compact ingot
plucky laurel
#

yes distance from center to farthest corner

#

not distance, sqrmag

compact ingot
#

the 6 planes are just the first thing that came to mind

plucky laurel
#

yeah i dont see any other way atm

compact ingot
#

and the || makes it an early exit

austere jewel
compact ingot
austere jewel
#

It removes the plane checks entirely by moving the coordinate system to 0

#

Why BB when you can AABB is what I always say

flint geyser
#

Unfortunately, or fortunately, I don't understand how it works

#

Because I at least do not know what Inverse of a Quaternion is

austere jewel
#

Instead of rotating one way, it rotates the other

flint geyser
#

Basically -1?

austere jewel
#

similar to * -1

#

the code "moves" the bounding box and sphere to the origin, removing the relative rotation from the sphere position, so you just have a sphere and an axis-aligned box at the origin. Then it's just a distance check, no rotation involved

flint geyser
#

❤️

austere jewel
#

The entire concept of moving points so they're relative to an unrotated shape at the origin is required to use any SDF functions, so it's pretty common logic to do

plucky laurel
#

thanks

austere jewel
#

(just to illustrate the transform I perform which makes the logic much more simple. Instead of the complex case of a randomly aligned and positioned box and position, we just move it to 0 and remove the rotation)

winter folio
#

https://youtu.be/MRw_ixL2Nyo
have been working on this and wanted similar gun pointing/movement mechanics to that unrecord game in UE5, but the way theyve made it move around is so realistic. Atm mine just simple which moves and rotates based on how far the mouse moves. Any tips on how I can make it more realistic in that sort of style?

Quick test on the new pistol, updated vfx, a little bit of the lighting, the map and a few extras for the feel of the game like the physically based weapon pointing to help simulate more of a helmet cam/body cam style.

▶ Play video
devout coyote
#

So when a new player connects, both the host and the new client run that event

#

So on the client you then try to change the networkvariable (which can only be written to by the server, so that's never going to work) and at the same time, but from the host perspective you overwrite it to DM

#

The code that you have should only be run on the Host, as the host is the only one who is allowed to change the playerName network variable

lime stream
#

Ahhh I see, one thing that I do not like of the NGO documentation is things like this are omitted

devout coyote
#

You then try to figure out whether or not the host connected, or if it is another client that connected, I'll have to jump in unity but I think there's a IsLocalPlayer that would work

#

It's all in there

#

Use IsLocalPlayer, which would only be true on the player object of the host

#

So you can filter out if it's the host or a new player

#

What really helped me was realising that every piece of code is ran on every machine by default

#

Every game is essentially a copy from eachother

lime stream
#

Ah okay, got it!

#

That really helped

devout coyote
#

You are welcome

green crane
#

making text display when you click on an object

compact ingot
austere jewel
austere jewel
#

I don't get it

compact ingot
# austere jewel I don't get it

so if you use a distance check, and the sphere is not aligned, the distance at which it still collides is different when it is not aligned with a face center (green vs blue)

austere jewel
#

It's distance to the box

#

not distance to the center of the box

compact ingot
#

it seems to me your solution is essentially doing the same thing with different methods from the API, the comparisons and local space transforms still have to happen the same way

austere jewel
#

Because apart from the small amount of maths to get the point relative to the origin, it's just:

float sdBox( vec3 p, vec3 b )
{
  vec3 q = abs(p) - b;
  return length(max(q,0.0)) + min(max(q.x,max(q.y,q.z)),0.0);
}```
(though length squared)
In comparison to constructing the 6 positions, 6 rotations, then performing 18 dot products and 6 normalisations
sharp imp
#

Im having a very weird issue of a class that is marked as [Serializable] and it contains list of objects that are also [Serializable]. I have a logic that relies on elements of this list being null. So sometimes you would have list<A> LIST = new list<A> followed by LIST.Add(null).

What Im observing is that if this list is null at seemingly random times it gets populated with an instance of the object A, as if Unity refreshed the list in the background because it is serializable. When I remove the Serializable mark, I no longer get this issue and I was also able to detect that the constructor of A is being called with no history in the stack trace. And if I dont have the Serializable mark then I can not serialize it with JSON serializer as is simply ignores it during the serialization. Can someone confirm this? And maybe explaing why is this the case? Thank you!

dusty wigeon
sharp imp
rough sky
#

I'm doing some CPU profiling because I was only reaching 40fps, and I found out it was lagging heavily waiting for the GPU to finish. When profiling the GPU I get this:

#

Mainthread is the entire problem

#

And I'm not entirely sure why it is

#

considering that all the calls it is making have significantly less than that, even cumulatively

#

so where has all the time gone?

sly grove
rough sky
#

Great, thanks, I'll use that

grave apex
#

Does anyone have an idea on how to seam together 2 navmeshsurfaces (that are on chunks) so my agents can pathfind from one to another if/when needed? For example in the video attached, the agent can't pathfind to the other chunk/navmeshsurface. I have tried both navmeshlinks and offmeshlinks, but there's like no docs on that stuff so I dunno how to use them in my situation (that is, if they would even make sense to use here).

#

Or would I just be better off generating and re-generating a single huge navmesh each time a chunk is loaded

dusty wigeon
dusty wigeon
#

But again, using RenderDocs might give more information.

regal olive
grave apex
#

Since one chunk is like 512x512 so I don't think the player will notice

regal olive
#

and on the parent (the gameobject) you could make a really big navmesh surface

#

never tried it before

#

but it may work

grave apex
#

But you would still have to update the parent's navmesh every chunk update I believe

#

Idk haven't looked into it too much myself too

regal olive
#

what do you mean chunk update? like a new object placed?

grave apex
#

Like when a chunk gets disabled/a new one loaded when the player moves around

#

Because if it doesn't get updated then eventually with many chunks the navmesh's size gets huge -> leads to even more lag

regal olive
#

i cant remember but do navmeshes have a resolution feature like terrain?

grave apex
#

Yeah they do, I have it on like the lowest setting because it has to be generated at runtime

#

I wish unity had just made it so agents can just jump between navsurfaces

#

But the package is experimental anyways soo what can you do

regal olive
#

maybe look into navmesh grouping

#

if that is a thing still

grave apex
stuck onyx
#

im trying to install this logger:
https://github.com/Cysharp/ZLogger

But im getting this exception when trying to build for iOS
```ArgumentException: The Assembly System.Diagnostics.DiagnosticSource is referenced by Microsoft.Extensions.Logging ('Assets/Plugins/Microsoft.Extensions.Logging.dll'). But the dll is not allowed to be included or could not be found.````

GitHub

Zero Allocation Text/Strcutured Logger for .NET Core and Unity, built on top of a Microsoft.Extensions.Logging. - GitHub - Cysharp/ZLogger: Zero Allocation Text/Strcutured Logger for .NET Core and ...

#

I tried installing the last version of the System.Diagnostics.Diagnostic source from Rider:

#

but the build keeps failing 😦

dusty wigeon
thin mesa
#

did you look in the releases for that repo? there's literally a unity package that includes almost all of what you need for it

stuck onyx
#

yeah, you need also Zstring

#

and installed it, ran in editor all fine

#

damn im so frustrated

#

gonna try again

dusty wigeon
#

Is it possible that the package is not supported for IOS ?

stuck onyx
#

it says supports I2LCPP builds

dusty wigeon
#

If you build a PC build. Does it have the same issue ?

stuck onyx
#

i didnt try to be honest, im gonna do a last attempt and try that tomorrow

rough bolt
#

I have a script for my WebSocketClient, I'd like the instance of that client to be accessed across my unity project. Is the best way to enable that via a static singleton that each class can access?

plush hare
#

Have you really maxed out the performance of your single threaded capabilities to the point where you actually need multithreading?

#

Because no, you cannot drive an animator from unity's non main thread.

#

Multithreading isn't some magic solution for running 1 million game objects

#

You first need to solve the spacial locality issue so you're taking full advantage of the CPU cache

#

which you won't be doing in standard unity

#

parallelizing code starts in SIMD

#

that doesn't matter

#

If you're not maxing out a single core's SIMD capability, then there's really no reason to spin up more threads

#

you'll need to move to DOTS if you want this many gameobjects at once.

#

you'll really need to go for pure ECS/DOTS if you want to do this right

#

the only thing it really lacks, as far as I know, is native animation support

#

Basically in OOP, the objects are spread out all over memory. You can't change this because of how C# works.

#

When your CPU wants to grab something from ram, it's also going to grab a bunch of stuff around it

#

hence spacial locality

#

in order to maximize SIMD throughput, you need to have good optimized memory transit to the CPU

#

when you're reading stuff linearly in an array, the CPU can pretty efficiently prefetch it

#

that's why DOTS is so much faster than standard unity.

#

as far as I know, C# internally is always moving managed objects around in memory due to garbage collection.

#

like I said, it has no animation support for right now.

#

that's probably going to be your only bottleneck

compact ingot
#

curious, what are you animating 1 million times?

#

so like character movements etc?

plush hare
#

I think you can instance animations

#

probably wont help at this scale

#

Like I always recommend as well, you can turn down the simulation rate pretty low

#

like 5-10hz

#

and just interpolate in between

compact ingot
#

do you absolutely need a skinned mesh renderer or could you live without one, i.e. not animate the vertices in a mesh?

small latch
#

The second game abuses the hell out of the GPU over the first game abusing the CPU

#

making of video from the devs

plush hare
#

I wasn't aware that you were using a third party solution

#

you should probably ignore what I said about the multithreading part then

#

unity still does have a bunch of limitations on multithreading though.

compact ingot
#

interesting stuff 👍

gloomy vessel
#

I have an organization created

#

and it still shows thos

compact ingot
#

they just have different use cases in gamedev and the frameworks built around them for games are therefore structured differently

#

thats something that trips up a lot of people who come from different programming fields and bring their mental models with them into gamedev... stuff just seems weird here since we care way more about performance when the rest of the world cares mostly about loads of data. i think you need to see a couple of fundamentally different approaches to and use-cases for software development before you truly stop running into that.

#

oh, whats your take?

#

interesting, ive never used that stuff, definitely can understand the excitement

brisk pasture
#

would just limit your multi threading to things that are not touching not thread safe unity apis

untold moth
#

Did you read the first reply in the thread?

#

The fact that you "can" do it, doesn't mean that you should. You could make an infinite loop(there's no error to prevent you from that), but should you?🤔

#

It's not about production or not. You'll run into race conditions and there's nothing to point them out.

#

I mean, if you're going that far, why not just use DOTS?

#

It would be more performant.

brisk pasture
#

if you just throw locks everywhere you are no longer truely multi threaded

#

now its just code on multiple threads running no cocurrently so reason is becuase concurrency is still a hard problem

compact ingot
#

and locks based multithreading isn't really great for performance, its more about coordinating sync points than making stuff faster with parallelization

brisk pasture
#

why it scales best to cases where its i need a bunch of individual jobs done that have no communication with eachother, let me know wehn its all done

compact ingot
#

O(1) can be a long 1

brisk pasture
#

you are really over simplify it, and not understanding what synchronization is

#

there is no magic bullet to hey now any workload can run in parallel

plush hare
#

sure, using SIMD. Not just shoving everything on a different core

brisk pasture
#

and i am not saying dont do that

#

i am saying pick and choose where you get most bang for buck with it

#

if used for everything it adds a large complexity burden

compact ingot
#

also parallelization in DBMS has very different properties from parallelization for compute workloads

plush hare
#

I don't see the issue

#

There's nothing wrong with more cores, it's just a massive waste if you aren't already taking full advantage of the first one

#

DOTS/ECS is pretty much designed for this

#

ECS components are homogenous data sets with the same sizes

dapper cave
#

how do you find all references to enable of only one script type?

#

somewhere in my code I'm setting this to false :/

plucky laurel
#

is that vs? the find references panel should have type column you can sort

sly grove
plucky laurel
#

wait that wont work

#

but it has write/read column

sly grove
#

Also enabled = true; inside Awake will never do anything

dapper cave
sly grove
#

It's intended behavior

unique oxide
#

Can someone help with implementing VR rig with oculus quest 2 and steam vr tracker 3.0 in unity !!?

stuck onyx
#

that way nobody will help you, ask direct questions.

blissful patrol
#

https://forum.unity.com/threads/unity-crashes-badly-during-run-time.1434310/
heya...so i have this issue which is mentioned clearly on the forum, but here's the briefing.

during run time, at a certain time (mentioned on the post), my unity engine stops responding...and ive to force quit it in task manager. i tried to export the game in hope that it was just an engine fault...but it still happenes... i think it is due to the code sucks... can anyone pls help me out? this was for a game jam... thx.

also, u an ping me. 👍

untold moth
#

This is not really an advanced topic.

#

I think I've spotted the cause, but I'll leave it to you to find, since you've posted in the advanced channel.😛

blissful patrol
untold moth
#

No. Use the debugger and you'll figure it out in a minute.

blissful patrol
#

i cant...it crashed so bad, taking this screenshots looked like taking screenshots on a life support potato pc... everyhting looked normal during the crshing though

#

wait a min~ i forgot one ss

#

can u tell me now? atleast on which script?

untold moth
blissful patrol
untold moth
untold moth
#

What is that?

#

Is the game frozen?

#

I didn't mean that you need to place a breakpoint, but to break execution.

#

If I'd meant a breakpoint, I'd say "place a breakpoint"

orchid marsh
#

Maybe show us the console tab.

stuck onyx
#

am I the only one that noticed this channel has dropped 50% activity since the coming of chatGPT ?

dusty wigeon
#

If only it was the case for #💻┃code-beginner.

To be honest, I do not think there is any correlation between those event. In fact, I would not even know if it was more active before. Also, ChatGPT is kinda dumb, it does not help much with real world issue. It is really good at being believable though.

AND, this is support channel, not a off-topic. So let's keep it that way.

stuck onyx
#

when the camera renders?

#

because i took for granted they did and nothing can happen in between

#

(maybe im begginer, though 😅 )

#

i mention this because i just had to ask chatGPT and gave me a detailed answer of how they are not and how stuff could happen in between that could mess the logic i had in my code

#

just a silly example

hushed fable
#

What do you count as something happening? OnPre/Post pair certainly implies that something has happened 😄

dusty wigeon
#

I would not blindly trust what an language model AI would say.

analog hazel
#

I have an inventory system but i would like to add a part where you put the weapons and you can equip them, if someone can help me 10minutes with that ??

bleak citrus
#

it will confidently lie to you

#

an LLM does not generate truth; it generates plausible text

dusty wigeon
versed coyote
#

I have two BoxCollider components on my GameObject. I want one to act as a "PreCollision" so I can make things happen before the actual expected collision (via the second BoxCollider) happens. However I haven't figured out a way how I can differ between those two BoxColliders yet. For now I would create a custom component that extends BoxCollider and call it ProxyCollider. However I wonder if there's a more elegant way.

EDIT: just realised I can't extend BoxCollider 😄

tender ore
#

I want to implement cutscene editor system using Scriptable Objects. Cutscene stores a list of actions represented by other SOs. For example I have SO class WaitAction that has float Duration field, but I don't want to create many SO instances for different Duration values, what can I do?

dusty wigeon
tender ore
dusty wigeon
#

If you do not want to create multiple SO for multiple Action, you need to store the information somewhere. The only available place (that make sense), is the cutscene itself.

[System.Serializable]
public abstract class Action { 
  public abstract void Execute();
}
public class ActionA : Action {
  [SerializeField]
  private float duration;

  public override void Execute() {}
}
public class Cutscene : ScriptableObject {
  [SerializeReference]
  private List<Action> actions = new List<Action>();
}
analog hazel
dusty wigeon
analog hazel
#

i have a different script that i was trying that has like primary-secondary-melee types of weapon

dusty wigeon
#

If you do, it is as simple as calling the function that does the equip.

analog hazel
#

k ty ill try some stuff

tender ore
#

But I don't want to do it

lapis kestrel
#

does anyone know anything about Photon Pun ?

timber flame
#

What is the most common way to simulate water and fluid simulation in voxel based games?
Cellular automata?
PSA?

uneven mauve
#

Is there an easy way to configure a modular pipe system for placing different pipe components such as corners and splitters in a grid?

dusty wigeon
# tender ore But I don't want to do it

This is why you need to not do SOs for your action... At least, not for the data. The data should be contained inside a global asset, which is the Cutscene.

dusty wigeon
# uneven mauve Is there an easy way to configure a modular pipe system for placing different pi...
Unity Learn

Rule Tiles are scriptable tiles written in C#, which are smart enough to use the appropriate adjacent tiles, and handle tile animation, boundaries, and collisions on the fly. In this tutorial, you will set rules on a tile and experiment with the properties and settings of a Rule Tile.

uneven mauve
#

Thanks!

bold slate
stuck jacinth
#

Hey, can someone please help me with dll in Unity. I have a normal cpp and header file that just adds 2 numbers and returns the result, I have created a .so file to implement in Unity. But when I run it in unity I get an error. The error is attached below in the screenshot.
I would be really happy to get some help. Have been working on this error since 5 days now.

versed coyote
violet field
#

Hoping someone has some debugging techniques I don't know of.
I am currently on contract building a singleplayer game to multiplayer, and it is clear the game wasn't built for networking in mind.

Here is my issue. I am spawning the vehicles correctly, and they are active in the scene. But something is tampering with the nested rig, which holds the skinned mesh renderer. The skinned mesh renderer is for some damn reason disabled, until the initialization function is run on that vehicle (when I switch to it).

I can't for the life of me figure out what is disabling this component... I am hoping some debugging I don't know of, can tell me when and what is disabling the mesh renderer in question?

#

Some kind of callback maybe, that return what has changed it?

#

I tried searching through my entire project for .enabled, but haven't seemingly found anything relevant 🤔

obsidian glade
stuck jacinth
dusty wigeon
# violet field Hoping someone has some debugging techniques I don't know of. I am currently on ...

Strangely, debugging is not a topic where you can find a lot of useful information/reference. There is different way to approach your current issue:

  • You could start from a working point and try to get to your current point.
  • You could remove things till you do not have the issue.
  • You could try to find the "commit" that caused the issue by binary test a range of commit.
  • You could search every possible known cause. (Like you did with searching .enabled)
  • You could use the Scientific Method. (Renderer is inactive -> (Knowledge on the topic) -> Maybe it is being deactivate by the Network Solution ? -> Disable Network Solution -­> Is my renderer still disabled ?, Renderer is inactive -> (Knowledge on the topic) -> Maybe a component on the GameObject deactivated it ? -­> Remove all component of the GameObject -> Is my renderer still disabled ?, Renderer is inactive -> (Knowledge on the topic) -> Maybe it was disabled in the prefab ? -­> Look into the prefab -> Was my renderer disabled ?)
  • You could try to intercept the call. This is can be done by wrapping the code that is supposed to do the action. (.enabled might not be possible to do). You could try to inherit from SkinnedMeshRenderer and add a OnEnable callback as an alternative.
  • You could try to find the moment where the issue happens by looking at every piece of code that has been executed between the point where it works and where it does not anymore. It can be hard to be done, especially with 3rd party library. Maybe this could help: https://docs.unity3d.com/ScriptReference/LowLevel.PlayerLoop.html
violet field
# dusty wigeon Strangely, debugging is not a topic where you can find a lot of useful informati...

Yeah, so as you also mention here. The networking solution turned out to be the cause, since they have some default parameters that triggered since the scene wasn't loaded correctly. I went looking through a bunch of code with searching "r.enabled =" and finally found one pointing to the networking solution.

no matter, some great feedback given here! I'll keep these steps in mind for a future case.

Thank you my guy!

bold slate
# versed coyote And I check the name of the collider's gameobject's name then I guess?

If you add a script to each of the empty gameobjects, you can just check for the collision there. There shouldn't be a need to a do a name check (I think).

You could also add a single collision checking script to the parent gameobect and that would receive collision calls from the two child objects because collisions bubble up the hierarchy. In that script you would then need to check the name of the gameobject that had the collision.

dusty wigeon
cold mural
#

What does this mean?
The project I'm working on throws an OutOfMemory error after playing it for a while. The log file for the development build shows this.
While profiling, the memory usage does not increase steadily but spikes up in an instant.
I would be playing and memory would be stable at 0.5 GB,
It throws OutOfMemory error, the game freezes,
Resumes after a while,
and the memory has spiked up to 4.5 GBs.
What might be the cause of this? Is it related to the code I've written or is it profiler related as the log says?

bleak citrus
#

does the game misbehave at all when you aren't profiling it?

sly grove
#

Use the memory profiler to try to diagnose the issue

cold mural
cold mural
#

So I cannot figure out what has happened after the spike

dusty wigeon
#

The profiler might add too much of a burden on your device. Do you have device with more memory ? For example, Switch have the possibility to get to 6G while the Switch itself has 4G.

bleak citrus
#

can you get an out of memory error if you create enormous amounts of garbage in one frame?

#

i'm not sure how that works

bleak citrus
#

i figured the GC would get invoked to clean it up

#

but i'm actually not sure where that happens

#

my understanding is that it can run any time you ask for memory (which is why you see long delays in your functions when the GC runs)

compact ingot
# bleak citrus my understanding is that it can run any time you ask for memory (which is why yo...

Garbage collection occurs when one of the following conditions is true:

The system has low physical memory. The memory size is detected by either the low memory notification from the operating system or low memory as indicated by the host.

The memory that's used by allocated objects on the managed heap surpasses an acceptable threshold. This threshold is continuously adjusted as the process runs.

The GC.Collect method is called. In almost all cases, you don't have to call this method because the garbage collector runs continuously. This method is primarily used for unique situations and testing.

cold mural
dusty wigeon
#

At least, to help.

cold mural
bleak citrus
#

that feels like the pathfinder is getting stuck in a loop

compact ingot
cold mural
compact ingot
#

a pool doesn't fix memory leaks

#

might just be a missing release somewhere?

cold mural
dusty wigeon
#

Are you sure the issue is the Pathfinding ? Sometimes the place where the Out of Memory happens is not the reason why the out of memory happens.

cold mural
cold mural
dusty wigeon
cold mural
dusty wigeon
#

Otherwise, you need to go blind.

bleak citrus
#

just eliminate one avenue for spooky action at a distance

dusty wigeon
#

And do trial and error.

scenic forge
#

Probably don't go stabbing in the dark until you hit the jackpot

#

Reproduce the error in some way without crashing first.

#

Does it happen in editor or only on device?

cold mural
scenic forge
#

In editor are you able to make a big spike happen but without causing it to crash?

cold mural
scenic forge
#

OOM error?

cold mural
scenic forge
#

Are you able to cause a spike without it going OOM?

cold mural
scenic forge
#

Does it always happen when you do a certain action in your game?

cold mural
#

I have taken several snapshots, before and after the spike
But strangely enough, I cannot open the 'after spike' snapshots. The Memory profiler just stays at the 'Busy for x seconds' dialog forever.

scenic forge
#

Profiler is probably dead after the OOM error, which is why I'm trying to guide you to reproduce a big spike without it going OOM.

cold mural
scenic forge
#

If you have a consistent way to trigger OOM, then start stripping things down to lower memory usage, until you can get a spike but without it going OOM, so you can actually use profiler and figure out what's causing all the memory allocations.

#

Otherwise you could spend all day poking at random parts of your code praying to get lucky.

cold mural
#

Most of the 'Objects' seems to be same, there's not much increase

#

Also, Empty Fragmented Heap space has increased

scenic forge
#

I don't really use Memory Profiler, look around and it should have detailed breakdown on stuffs, but it seems like you got a huge allocation somewhere.

#

On the frame that allocation spikes, should be pretty easy to track down what's allocating.

dusty wigeon
# cold mural So, I did manage to get before and after snapshots. The biggest change in the af...

The managed heap is most of the time associated with memory you allocated in a script, such as array. The fact that you have that much memory being reserved means that at some point, you had a really high demand in memory. If you use the Profiler (Not memory profiler), you should see a high amount of GC.alloc happening at a specific time. By using the "call stack" with GC.Alloc enable, you should see where they are coming from.

analog hazel
#

I currently have an inventory system in which you can pick up items, see items in inventory, drag them around, drop them,... but i'd need help making it so you can equip those items with the stats if I could screenshare 10m

regal lava
#

Better to post your issues here if you want help

rotund oxide
#

I'm trying to make it so that somewhere in the gray section inside the square, a gameobject will spawn. However, since the blue section uses a edge collider I don't know how to make sure that it isn't touching the blue section, can I get any help?

untold moth
rotund oxide
untold moth
rotund oxide
untold moth
#

What I suggested would work regardless.

rotund oxide
untold moth
rotund oxide
untold moth
#

But if you can generate am edge collider, you can probably generate a polygon collider too, which should allow overlap collision detection

rotund oxide
#

I'll test it, might be a while though.

rough bolt
#

I want to be able to control characters through either player control or AI control, is it possible to do this through the Input System?

#

Where I keep all the same actions

grizzled raptor
# rough bolt I want to be able to control characters through either player control or AI cont...

AI can't really push buttons on an input type like a mouse so no.

But if you want to use the same code for both player and AI without having to change things set up a statemachine.

You can change states based on direct input (from the player) or on information provided to the AI.

E.g. moving.

Player presses button > set state > state runs function.

AI sees player and wants to chase > set state > call same function

Then you can turn the state "off" when the players let's go of the button or the AI can't see the player.

rough bolt
#

rather than having redundant code

grizzled raptor
#

Yeah so use a state machine and put the logic from fire() into it. Then when the player presses the button, set the state to firing() which then calls the function logic.

Then when you want the ai to use firing() it just calls it based on information given to it rather than input

#

That way you have the same logic for firing

#

But it's called differently based on the agent

rough bolt
#

Different question, for the input system, it is it's own mono behaviour that calls functions associated with input actions?

grizzled raptor
# rough bolt Different question, for the input system, it is it's own mono behaviour that cal...

It's a bit more complicated than that and would take a lot of typing to explain. However you can generate a class file from your input controller if you want to see some of its inner workings.

In regards to the statmachine stuff it's again another topic that would take a lot of typing to fully cover but this tutorial is very good and explains thr concept. It'll take some time to set up but I think it's what your looking for
https://m.youtube.com/watch?v=Vt8aZDPzRjI&pp=ygUTc3RhdGUgbWFjaGluZSB1bml0eQ%3D%3D

Learn the fundamentals of programming State Machines in Unity with this new video break down!

This tutorial explains important concepts of the State Pattern, and how to use State Machines when programming! Today we will walk through an example project to showcase the benefits of using state, the state pattern and state machines in Unity!

This ...

▶ Play video
rough bolt
#

is there a more programmatic way to do animation events?

plucky laurel
unique moss
dusty wigeon
# rotund oxide I'm trying to make it so that somewhere in the gray section inside the square, a...

In game, you usually do not have the possibility to comfortably define what is an available zone. The exception is if you are already using pathfinding, then you can easily find a point on the desired zone as the pathfinding already has done the work.

Most of the time, random placement is done by using "zone" of availability as this is the fastest and the least error prone. An alternative is to use a point of reference that we know is inside and then raycast randomly.

dusty wigeon
magic valve
#

Hi guys, I would really appreciate some help if anybody tackled with this before... I am not entirely sure if I should post this in advanced or beginner. I am beginner myself but I feel like topic is quite advanced so I will post it here. I am trying to make stable diffusion work in AR. To do so, I first need to make dynamic tracking for which I need to add images in my library during run-time, and with that I am having issues. There is only a few documentation out there but this is basically what Ik so far. I need to use MutableRuntimeReferenceImageLibrary object, which will be created from ARTrackedImageManager object (because ARTrackedImageManager cannot be edited in run-time, while MutableRuntimeReferenceImageLibrary can). What I am trying to do is taking a picture on button press and then set that picture as new tracked image. I am currently using version ArFoundation 5.0.5, Google ARCore XR Plugin 5.0.5, OpenXRPlugin 1.7.0. I should also mention this is supposed to be android app. Stable diffusion will be done on pc and then sent over api to mobile device.

stuck jacinth
#

Exception occured while loading the dll file is : System.EntryPointNotFoundException: Unable to find an entry point named 'GetRandom' in 'myapplication'

#

I am getting this error when I implement it in Unity by using dll import

#

I have no idea what I am doing wrong. But, I know for sure that there is something I am not doing correctly, I just don't know what it is

#

Please help me out as I have been trying to do this for the past 5 days and getting this same error every time I try to do it. I have tried almost everything that I know, googled for the solution. I absolutely have no idea what mistake I have been doing.

autumn topaz
#

how do i split a BitArray into portions of equal size? eg. turning
10 01 01 01 11 00 10 10 11 00 00 into an array
2,1,1,1,3,0,2,2,3,0,0?
or even better getting a select portion of bits based on an index eg index 4 returns binary 11 -> int 3?
the size the portion of bits are can vary eg 0 , 10101, 111 etc.

obsidian glade
timber flame
#

What shader should I use for 2d grass? cut out shader or transparent and 2d rect shape or polygon shaped sprites?
Games like cult of the lamb

compact ingot
timber flame
compact ingot
#

Either

#

This isn’t graphics bound in any way

#

You don’t even need transparency

#

Just alpha clip

timber flame
#

and as you mentioned about rotating/aligning the sprites. You mean they don't look at the camera? Instead rotate around their pivots at bottom center in screen space?

timber flame
#

Yes, in cult of the lamb, it is not high

compact ingot
#

Profile your design so find out how many you can have

#

If you do the billboarding on the shader it will be cheaper

versed coyote
#

Is there any way to assign a Component dynamically by a string instead of a type for example gameObject.AddComponent<stringToType("MyComponent")>() ? For my importer I kinda need to map Google Sheet strings to mappings of Components if that is possible. I want to avoid a large switch statement to map every possible string value.

sly grove
versed coyote
sly grove
#

Yes

versed coyote
versed coyote
sly grove
#

Same deal

#

the first overload

#

though it does seem to be marked obsolete

#

It will still work

#

It's basically just going to be doing reflection under the hood - so you could also do the reflection yourself if you want.

versed coyote
# sly grove It will still work

Assets/Editor/Bangerang/CardEffectImporter.cs(200,38): error CS1501: No overload for method 'AddComponent' takes 1 arguments

#

Do I need to disable some compiler checks here?

#
        public static T AddComponent<T>(this UnityObject uo) where T : Component
        {
            if (uo is GameObject)
            {
                return ((GameObject)uo).AddComponent<T>();
            }
            else if (uo is Component)
            {
                return ((Component)uo).gameObject.AddComponent<T>();
            }
            else
            {
                throw new NotSupportedException();
            }
        }

I am sure this is some dead code

fresh salmon
sly grove
#

There's no generic type parameter for the one you want

fresh salmon
#

Yeah so as mentioned you need to use the overload that's not generic. AddComponent(string), then cast the return type to whatever type you need

versed coyote
rotund oxide
#

I have this piece of code that I'm having trouble with. Essentially, I have a 100 x 100 area with the center being 0, 0 and I want the object that has this script to go to a random spot on the area. However, there are some areas I want them to stay out of, those areas are randomly generated so I can't predict them, and they don't have colliders. To fix this, I tried to make a multidimensional array that would set an area to false if it could spawn there, and true if it couldn't. However, it will sometimes tell me something is false, yet it spawns in the bad area (Sometimes it will spawn in the good area)

Some relevant information might be that the width variable is 100, the height variable is 100, and hasTile is the multidimensional array.

#

sorry, kind of long

regal lava
#

I'm trying to understand, is the alg setting this 2D grid or are you doing something manually after it's being generated? Seems like something you'd want to integrate into that functionality when it creates a level.

torpid smelt
#

When making a mesh via mesh.combinemeshes, do I need to do anything special in order for that combined mesh to be able to be combined with another mesh down the line? currently having issues with it

#

issues as in the mesh inexplicably doesn't show up when I merge with others

#

No warnings are shown in the log, it's not a null entry, I know for a fact the mesh exists

#

but when combined? nothing

#

the only possible way it's different is due to it being a mesh that was the result of it being combined, so I need to know whether that's actually the issue or I'm just cursed

rotund oxide
regal lava
#

Right, you should be adding the constraints as the level is generated and have a populated grid when it's completed

#

the grid idea is fine if you're not trying to use colliders

grizzled raptor
rotund oxide
#

When I said there weren't colliders, I wasn't exactly telling the truth, there are edge colliders, but not ones for the inside of the bad area, just the edges. I shortened it because it didn't seem like an important distinction.

regal lava
#

Overlap should be fine then, no?

rotund oxide
grizzled raptor
#

If both pass. Spawn player

#

It'll probably be more complicated than that but you can add more checks to player location based on your project needs

untold moth
# rotund oxide I have this piece of code that I'm having trouble with. Essentially, I have a 10...

Might want to add some debug info. For example print the spawn position and the indices of the grid that you check against, and compare it to your occupancy array. Really, you're supposed to be able to do this kind of debugging if you post in this channel...

I think there's no issue with finding an empty tile. The issue is probably that your spawned object occupies more than 1 tile, so it seems to you like it spawns in the occupied area.

rotund oxide
# untold moth Might want to add some debug info. For example print the spawn position and the ...

I thought I already had enough Debug info but I'll look into adding more, as for the second part I've included an image, the green dot is the object, the blue dots are the surrounding whole number coordinates, and the blue area in the background is the bad area. I don't believe the object takes up multiple spaces, and the top left one is also considered in the bad area according to some debug info I got.

untold moth
rotund oxide
#

I figured something out, after looking over the code again I had some unnecessary code, after removing it it worked!

rough bolt
#

I'm implementing my movement system for my 2D top down RPG via rigidbody2D.move position, the exact code I use is:

character.rb.MovePosition(character.rb.position + movement * character.Speed * Time.fixedDeltaTime);

where the movement is

        float moveVertical = Input.GetAxis("Vertical");

        movement = new Vector2(moveHorizontal, moveVertical);```

and I've verified that it's running during every fixed update, but I still seem to get micro-stutter. Why?
shy glacier
#

Try pixel perfect camera, unlikely to fix, but worth a try

rough bolt
shy glacier
#

Try normal update with deltatime instead of fixedupdate

rough bolt
#

that doesn't seem wise

shy glacier
#

Why not

rough bolt
#

doing physics in update is not ideal

#

also there's just no reason there would be a difference

#

if it's running on every fixed update and being modified with fixedDeltaTime then it should be fine

shy glacier
#

Are physics necessary to implement movement in your project?

tall ferry
rough bolt
#

but I just realized, I think it's due to cinemachine

#

I turned off the cinemachine follow and it's butter smooth

tall ferry
#

i havent used pixel perfect so i cannot comment on that, i know that i have jitter when my character ragdolls insanely fast only

#

well it seems smooth because ur camera isnt moving anymore

#

the issue is that your player is moving but the follow isnt updated fast enough (i believe)

rough bolt
#

which implies it's an issue with the camera follow rate right?

shy glacier
#

Try making smooth follow instead of regular stiff follow

tall ferry
#

yes, 1 sec there was a nice link i have somewhere

#

did u try it with interpolation on and camera following the player?

rough bolt
#

yeah

#

looks like this

#

it feels like there's still micro stutter on it

#

i think it has something to do with the fact that I have cinemachine set to smart update and it's using late update?

tall ferry
#

late update should be good

rough bolt
#

hmm

tall ferry
#

once near the start and once at around 8s in my video

rough bolt
#

weird

#

why would it do that?

tall ferry
#

my suggestions wouldve been using late update and interpolate.. but if this happens with both then im unsure

#

maybe see if it still does the same as a build?

rough bolt
#

will do

tall ferry
#

actually that 1 frame at around 2 seconds indicates to me your animations and transform does not line up

#

the camera moves when the player doesnt

rough bolt
#

i think that's just due to the animation not starting yet though, right?

#
    public override void FixedUpdate(Character character)
    {
        character.PlayAnimation("walking");
        character.rb.MovePosition(character.rb.position + movement * character.Speed * Time.fixedDeltaTime);
        character.FinishAction();
    }```

cause I play the animation immediately before the move position
#

(the play animation function doesn't do anything if it's the same animation)

tall ferry
#

i do think it is a desync between animation and transform because u have 1 frame where the camera moves to the left. then from 2-7 seconds in the slowed video, your player movement seemingly lines up with the camera movement. But at 8 seconds u can see the animation (or transform) shift to the left

#

it seems like the camera is following properly but its hard to tell, im not really an expert on this. maybe draw a sphere where the real transform is as u play, then slow down the vid to see those jitters

rough bolt
tall ferry
#

no because your only visual is the animation, theres nothing to compare it to

rough bolt
#

if it appears butter smooth without the follow camera, then what suggests it's not working properly?

#

comparison

whole plaza
#

both look good

tall ferry
#

i know the movement is smooth when the camera isnt following, thats because the animation is always smooth. its an issue with the camera following the transform. But i dont believe the camera is following at the wrong time, i think the transform isnt always at the exact place of the animation.

#

it does not, look at the video i sent above, there are clear jitters

whole plaza
#

ehh nope

tall ferry
#

it does look good overall but being hyper nitpicky

whole plaza
#

oooh

#

i only saw it in fullscreen, ew

tall ferry
rough bolt
whole plaza
#

what is the camera attached to ?

tall ferry
#

you will need to draw the actual transform on the screen to be able to debug this and see if im correct, i might be wrong even

whole plaza
#

maybe make the camera seperate from the body

#

the camera is attached to the parent of that sprite collection

#

no ?

#

i mean atleast thats how you do it in 3D

rough bolt
whole plaza
#

hmmm

#

really weird

#

cuz its the background thats jittery, so i guess the camera script is not moving the camera smooth

rough bolt
tall ferry
tall ferry
whole plaza
whole plaza
#

thats how most here fix problems, just trying out stuff suggested, but if you dont want to listen to people helping you lol

rough bolt
tall ferry
rough bolt
#

u might be right, transform seems to be updating before the sprite renderers?

whole plaza
tall ferry
#

uh that looks off, why is the circle always at the start

rough bolt
#

it's a gizmo

tall ferry
#

oh i see the red lines

rough bolt
#

the red lines are the transform pos

tall ferry
rough bolt
#

strannnge

#

no idea what would cause that

tall ferry
#

can i see your hierarchy for the player/ what the animator is playing off of? i havent used 2D so im not entirely sure if my next idea will help u

rough bolt
#

i have 3 sprite renderers that are attached to the human game object

tall ferry
#

but u might be able to align the transform to the animation, then shift the animation back

#

or maybe its an issue with how the animation was made

rough bolt
#

i have an idea

#

gonna check it

#

nope, check