#archived-code-advanced

1 messages · Page 65 of 1

glass lily
#

To separate the meshes, (unless there’s a built-in function for it) you’d need to manually group the triangles into separate groups. (Because the underlying mesh has no spatial awareness, of neighboring triangles).

#

The simplest way would be to just group triangles together if they share a vertex. (Using a Dictionary would be efficient)

brave cobalt
#

Hi, I am facing an issue while coding because the transform aspect is now obsolete. I want to use a local transform to move a character, but it throws an error: 'Cannot modify members of localtransform because it is a foreach iteration variable.' Could you please help me resolve this issue?

using System.Collections;
using System.Collections.Generic;
using Unity.Entities;
using Unity.Transforms;
using Unity.Mathematics;
using UnityEngine;

public partial class MovingSystemBase : SystemBase
{

protected override void OnUpdate()
{
    foreach(( LocalTransform localTransform , RefRO <Speed> speed) in SystemAPI.Query<LocalTransform,  RefRO<Speed>>())
    {
        localTransform.Position += new float3(SystemAPI.Time.DeltaTime * speed.ValueRO.value, 0, 0);
    }
}

}

glacial wedge
#

what happen to coroutine on gameobject disable?^

#

should i manually cancel it?

glacial wedge
#

Oh. thats good!

sly grove
glacial wedge
#

because I have an object pooled and want to be sure that some behaviour of previous lifecycle doesn't interfere

flat gull
#

Guys, let's say a have a function
f(x) = x^2
Or f(x) = sin(x)
How do i move a transform along (x, f(x)) with constant speed ?

green pagoda
#

transform.translate.vector3(x , f(x), 0)

x is the speed in x direction that you have to define and yk what's f(x)

#

maybe that work idk

#

I am just a bignner trying to help from what I know

#

@flat gull

sly grove
green pagoda
#

how do you type it like that in a box

sly grove
#

!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.

green pagoda
#

or its a ss?

flat gull
#

That's not what i meant, i mean like the constant speed bezier curve problem

sly grove
#

Maybe describe this "constant speed bezier curve" problem if you want to know about that problem

flat gull
tiny pewter
#

maybe integration
suppose you want to move ds in dt and for each x you add a dx on it and found a dy ie f(x+dx)
then check if check cumulative sqrt(dx,dy) < ds and assign (x+dx,y+dy) back to the position

sly grove
tiny pewter
#

but the difficulty is how to get proper dx so that it will not overshoot in final step

sly grove
#

oh you mean a constant absolute distance per second?

#

that's not the same as what you originally asked though

flat gull
#

I thought of finding an intersection with a radius of a circle but that probably not the best solution

sly grove
#

Is there a reason you don't want to just use Unity's spline package?

#

It has all this solved

flat gull
#

Wait really ?

tiny pewter
#

since dy is gotten from f(x+dx)-y so dx=f^(-1) (dy+y)-x

flat gull
#

With that package, can you make any function work and not just for the bezier curve thing ?

sly grove
#

no. The splines package handles:

  • linear
  • Bezier
  • Catmull-rom
    style splines
dusty wigeon
#

It works well.

#

Convert any form of function into a series of line.

#

Then, you use those instead.

#

Way easier in term of mathematics.

flat gull
#

I'm currently looking for a way to convert it, how tho ?

dusty wigeon
#

Sample points on your function ?

flat gull
#

Yes

#

Then i can probably just lerp between it

dusty wigeon
#

This is what you need to do.

#

You sample points then convert to lines.

flat gull
#

Ok so how do i sample points ?

dusty wigeon
#

You evaluate your function.

flat gull
#

Yeah say i already have array of positions

#

But between them are not in a constant distance

dusty wigeon
#

while(x < distance) ...

flat gull
#

Yeah then how ?

dusty wigeon
#

You just iterate through them

flat gull
#

By converting to lines, you mean just pass it to a certain variable in the spline package ?

tiny pewter
#

your problem is extremely hard....

flat gull
#

Whoa

tiny pewter
#

translate the equcation to (dx^2)+(f(x+dx)-y)^2-remain^2=0 (i mistyped the equcation in picture , and value of x,y,remain are known) and find the root, then dx=root and get dy

#

oh the dy is calculated, you dont need to define dy as a constant

dusty wigeon
#

The brown is an approximation of the curve.

flat gull
#

I still don't understand how todo the iterating part

flat gull
#

Can i just get those points easily without doing what ティナ explains :)

tiny pewter
#

you just need to find y1 by f(x1), y2 by f(x2),,,,

flat gull
tiny pewter
#

remaining distance to complete the whole s (displacment)

#

since it overshoots

dusty wigeon
#
while(distance < Wanted) {
  if(distance + segment.Distance < Wanted) distance+=segment.Distance;
  else return segment.Evaluate(Wanted - distance);
}
#

Something like that

tiny pewter
#

yes

flat gull
#

Oh

#

Remaining distance to complete the whole displacement of one small segment ?

tiny pewter
#

yes

#

but method in above picture cant be used in update loop indeed, since i thought the above one under the situation that showing animation without the help of game engine

#

ds/dt is speed

plucky snow
#

hello everyone, Im studyng all forms that a character controller
can be done, and i was wondering what you guys thinks is the best?
for a quick example there is the more "thypical" form in wich is a script with a lots of code
that includes the inputs, the implementation of the movement, jumping, etc.

but im looking for the best way to do a modular and readable character controller

another examble whould be the option of making various separated scripts that are conected, one that handles the inputs
other handle the movement logic, other the jumping logic, shooting, etc

what you guys thinks is the best way to do it properly?

untold plank
#

IMO, it depends on how do you want to maintain that code. If you ask me, I prefer a single script with clean code. I don't know if that's performant.

sly grove
tall ferry
# plucky snow hello everyone, Im studyng all forms that a character controller can be done, a...

Using your examples with the various separated scripts, I would definitely put the movement and jumping together assuming there arent many different ways to jump.
Input handling can be separated, but you wont notice a difference unless u need to swap input modes (ai vs player for example).
You definitely dont want every single thing in one script for readability purposes, but in terms of functionality there is no difference.
You can code the same thing in 1 script you can do in many, it's just not smart to do it that way

thin mesa
#

!collab

thorn flintBOT
vestal condor
#

I've been working with the FormerlySerializedAs attribute, and I'm wondering if there's a good way to clean them up?

real blaze
#

(clearly you have to enable Force Text as your serialization option in Player settings)

vestal condor
#

I was under the impression that somehow iterating through all existing prefabs and saving them would do something lol

sage radish
vestal condor
#

thanks, i’ll take a look

dusty wigeon
# plucky snow hello everyone, Im studyng all forms that a character controller can be done, a...

The importance of correctly dividing a Character Controller only arise when you far in development for a large game. In prototype project or Solo project, you usually do not need complex division. However, here a list of what you might want to divide:

  • Input. (AI, Cutscene, Menu, Online, etc.)
  • Statistic. (Breakable, Online)
  • Action. (Taunt - Bark, Weapon - Combo, Usable, Interaction)

What you do not want to divide:

  • Jump and Movement. (Both are closely related and can influence each other drastically)
bleak citrus
#

I tend to just split the character into a Brain and a Mover

#

the mover asks the brain what it desires and moves accordingly

weary roost
#

sir do you ever stumbled upon for a top down game with gyroscope at smartphone ?

devout coyote
#

So add attribute (or let rider add them when you rename) -> reload editor -> delete attribute

umbral trail
#

You'll need to mark them dirty (or use AssetDatabase.ForceReserializeAssets like dirty-boy above does) for unity to re-serialise them, it wont do it if there aren't any changes

plucky laurel
#

AssetDatabase.ForceReserializeAssets

unborn relic
#

hello, I have a mesh that i construct from scratch that acts as my ground. it has hills and water etc. i want to place grass in a procedural way on it, and at the moment the best solution I found was to do a iterate through a matrix above the mesh, raycast down from each point, and instantiate a patch of grass depending on the hit point and hit normal. Is there a more efficient way?

plucky laurel
#

shader, gpu instancing

#

unity terrain uses texture to drive grass density

unborn relic
#

i am talking about finding out at which point i should place the grass patches more efficiently (instead of using raycasts perhaps)

plucky laurel
#

if you can prebake heightmap from the terrain , you can use pixel value to set grass position

#

same probably goes for normal

unborn relic
plucky laurel
#

why not?

unborn relic
#

wouldn't it be constrained to 256 "heights"?

plucky laurel
#

you can use custom double[,] buffer

#

or unpack rbga32 into a float

#

or you can just store the data as is, v3 and normal

unborn relic
#

okay thank you for the suggestion, I will try it out

unborn relic
plucky laurel
#

noise function? uniform distribution

#

i.e. for each 1x1 square sample uniform function 5 times

#

if the function is good it will give semi random but uniform distribution across all positions

#

if youre using vertex data directly you can probably compute triangle area and use that as a ratio

unborn relic
#

i'm affraid my lack of understanding is regarding something a bit more basic: how would I know where to place the grass vertically on let's say mesh triangle a, b, c?

plucky laurel
#

tho the whole thing can probably be done offline

plucky laurel
unborn relic
plucky laurel
#

thats why i suggested prebaking this data first into a LUT, so you can skip the geometry

#

wont get any more performant on the cpu that to just position * heights[x,y] or something

#

i considered using verts, but you will need to locate nearest 3 verts of the triangle (needs acceleration structure), interpolate the value between them

#

you can probably just do raycasts in Jobs

#

that will accelerate the whole thing a lot

unborn relic
plucky laurel
#

i distinctly remember you can

#

maybe not this exact method, but you can

unborn relic
#

oh shit, nice! somehow i missed this.

#

you've given me much to think about. thanks you very very much for your help!

plucky laurel
#

no problem

glass lily
# unborn relic hello, I have a mesh that i construct from scratch that acts as my ground. it ha...

There’s another more efficient way. Iterate over each triangle and place the grass(s) on a random point on the triangle (which you get with p = v0 * w0 + v1 *w1 + v2 + w2, where 'v' are the vertex positions and 'w' are the weights, basically interpolation). But you also need to account for triangle size, otherwise big triangles will look sparse. So you probably want to weight the number/chance of grass on a triangle based on its area. The approach is a lot faster than raycasting but requires you to think a little differently about placement. (.cache’s answer of baking the heightmap could also be faster if you have way more triangles than grass, albeit maybe a little more involved)

unborn relic
soft moon
#

does anyone know how to get true size of 3 text lines? I have been trying to find it everywhere, but I did not succeed

tall ferry
#

let me know if it doesnt work, i do think it is this because content size fitter uses Preferred Size and adjusts properly. Though if there are margins you might have to add that yourself

soft moon
#
private float CalculateLineHeight()
{
    TMP_Text textComponent = typingField.textComponent;

    textComponent.text = "A";

    return textComponent.GetPreferredValues().y;
}
tall ferry
#

i assume that yellow box is the height?

soft moon
tall ferry
#

you might have margins between the lines then which adds more space, im not entirely sure

soft moon
#

here is line = 0

#

and yes, it works perfectly with more lines without line

tall ferry
#

im really not sure which property can give u the pixel size of the gap, but try lineSpacing

#

the package page doesnt really say what these return exactly

#

hopefully it returns it not in em

tall ferry
#

there seem to be a lot of other related properties, sorry not really sure which one you need. Im surprised GetPreferredValues does not take care of this, unless we did something wrong here

glass lily
real blaze
#

I just noticed, Rider apparently can't debug unity packages properly?

#

I set breakpoints but it's totally ignoring them

soft moon
#
private float CalculateLineHeight()
{
    TMP_Text textComponent = typingField.textComponent;

    textComponent.text = "A";

    print($"{textComponent.GetPreferredValues().y}; {textComponent.lineSpacing}");

    return textComponent.GetPreferredValues().y + textComponent.lineSpacing;
}
#

I wonder if lineSpacing should be devided by something

#

of wait, I have discovered the formula

#
lineSpacingInPixels = lineSpacing * fontSize * .01f;
#

and it works now:

private float CalculateLineHeight()
{
    TMP_Text textComponent = typingField.textComponent;

    textComponent.text = "A";

    return textComponent.GetPreferredValues().y + textComponent.lineSpacing * 
        textComponent.fontSize * .01f;
}
#

is case someone needs:

float rectOffset = .5f * (Screen.height - CalculateLineHeight() * numberOfVisibleLines);

RectTransform rt = typingField.GetComponent<RectTransform>();
SetTopBottomRects(rt, rectOffset, rectOffset);
flint sand
#

Hi folks. I'm trying to figure out a way how to use multiple NavMeshAgents to move to single target(wall in this case). When I use target position, it obviously not working well, since all the agents coming from relatively same direction and pushing each other. I am in a process of creating a logic that will provide a unique position near the target, so all the agents will have their own “spot”
Is there some easy way to do it, that I am missing something obvious here?

real blaze
flint sand
unborn relic
#

is there anything wrong with sending a mesh as an event argument when invoking said event? my editor seems to behave quite strangely when I do.

sly grove
unborn relic
#

it seems my problem stems from doing i < mesh.triangles.Length as a for loop condition. is mesh.triangles.Length an expensive operation?

long ivy
#

yes, very

long ivy
#

mesh.triangles/vertices creates a new array each time you access it

sly grove
#

Every time you do mesh.triangles it copies the whole triangles array

#

Just cache it once

#

And reuse

unborn relic
#

oh damn, i did not know that

#

well there goes 3 hours

#

glad to have finally caught it though. thanks guys!

regal olive
#

heya everybody,
im currently working on creating a procedural landscape for a game im working on in unity 3d.

right now im implementing caves using perlin worms but everything I try ends up broken or not working the way I wanted.

i did a bit of research and stumbled across a tweet of a dev who did exactly what i wanted to do
(view tweet here: https://twitter.com/pandeymahan34/status/1625155669446868998?s=20)

but i cant even begin to figure out what he did to code this let alone replicate this.
so i was wondering if anyone could provide methods similar or documentations, tutorials, etc about how to do this or something similar

Working with cave combinations

▶ Play video
austere jewel
#

I would imagine it's relying on marching cubes to build the geo, beyond that, what are you actually struggling with? Because it seems like once you understand that marching cubes is the way to go, everything else is just a matter of implementation details

regal olive
# austere jewel I would imagine it's relying on marching cubes to build the geo, beyond that, wh...

ive dug into that but idk if thats right.
every time ive seen people using that its been for voxel terrains and not smooth ones.

it almost looks like he is deforming the mesh around the sphere but to do that he'd have to have mesh in the first place but im not seeing any at all so honestly ive just got this video to go off of and reading trough different documents about similar topics and games that create procedural 3d caves.

most notably of them being Minecraft, apparently they use perlin worms to create their caves but i haven't found any relevant details due to it being voxel terrain and not a smooth type of generation

ive tried implementing a way for a sphere to deform the mesh but ive came back with either the verts being destoyed or nothing happening at all

verbal temple
#

smooth voxel terrains are still voxel terrains, and marching cubes is smooth when interpolated

#

this is a very documented topic and you can probably easily find examples of marching cubes looking exactly like that with a quick search

regal olive
#

ok ill go back to digging tough that again thanks for pointing me in the right directions meowparty

verbal temple
#

the worm is just subtracting from the density field (which in turn generates marched faces around it) as it travels along a path

#

and it looks like, based on some randomized distance chosen when the worm is created, it will despawn and spawn a new worm on any of the previous worm spawn / end points

#

with a new random direction

austere jewel
#

As Mahan's previous tweets are also all about marching cubes, I imagine they're just following on from that, adding caves to their marching cubes voxel terrain

regal olive
#

ok cool

#

this was really valuable, thanks!

#

👍

real blaze
flint sand
real blaze
#

@flint sand you need each of them to go to a exact location?

#

like in total war

flint sand
#

Yeah. Imagine a wave of enemies attacking my base, and the first thing they reach is a wall. So all of them(or most) will try to attack it

real blaze
#

@flint sand in that case you might need to use logics beyond just ai. make a system that tracks the enemy pack, marks the positions that are occupied, and make the next enemies go to the positions that are not occupied

#

you could imagine the world as a grid

flint sand
#

Yup, that’s how I approached it for now

#

Thanks!

real blaze
#

np!

gleaming rock
#

Can I read NativeArray<T>

outside of job which accesses that (it is marked as [readonly])

while the job is running?

I think yes but unity gives error that I can't because job writes to the array even though it is readonly

tiny pewter
#

oh i misunderstand your question

#

i believe the readonly attribute only remove some locks on that native container when running parallel job but the unity doesnt know will the elements be changed if you access it outside job system so you cant access it when the jobs are not finish

gleaming rock
#

ok

runic tendon
#

Is UI toolkit now the preferred way to code editor UI? Is there any reason to switch from the old style(like maybe more layout elements, easier to control layout)?

Additionally, if my editor UI doesn't need to be fully redrawn everytime, is there a perf improvement to using Visual elements/UI toolkit?

plucky laurel
#

yes thats the main point of uitk - its retained

#

this is simply not possible with imgui

#

also if you want to see a real example of where its performance rocks look at memory profiler

#

other than that you will have to deal with css, schemas and other things i hate

bleak citrus
#

[audience laughs]

plucky laurel
#

i get the joke

bleak citrus
#

a contraption!

plucky laurel
#

node processor on github

soft moon
plucky laurel
#

yes

soft moon
plucky laurel
#

just open the repo and read

soft moon
plucky laurel
#

node processor on github

soft moon
plucky laurel
#

i cant

wide elbow
#

I have a RenderTexture displaying a UIDocument with some text on a mesh in world space...
How can I increase the sharpness of the text? Would that be a UIDocument / PanelSettings option or something within the texture itself?

soft moon
#

Hello,
I have a small typing game with TMP_InputField, where user should type words that are visible on the screen.
Every time user types a character, the method TMP_InputField.onValidateInput is called.

// Start()
typingField.onValidateInput += ValidateInput;

That's not exactly what I do, but let's say I should call this method in onValidateInput:

private void ChangeText()
{
    // typingField.text = String.Concat(typingText.Select(w => w.parsed));
    typingField.text = niceText;
}

Everything works fine when niceText has, for example, 100 words (commented typingText is actually a text that's generated from json file).
When there are already, for example, 400 words, game's fps can validate between 300-400 when user is not typing and 1-40 according to the typing speed.

It would be great to change TypingField's text like typingField.text[0] = character, but as far as I know it's not possible in C#.
Any ideas how to increase game's productivity?

And yes, I know that I can do kinda visible text (that I do have), delete already typed text and generate new. But I also want user to be able to the the whole text (if that's possible ofc).

real blaze
real blaze
#

as for TMP optimizations, you can go very far by turning off richText and maskable and Parse escapable characters and kerning

soft moon
#

it's caused by

typingField.text = niceText;
novel plinth
#

use the non alloc version SetText instead

real blaze
real blaze
novel plinth
#

either way it shouldn't lag your game.. must be something else

soft moon
#

like 100 words = ~600 characters is ok

#

and e.g. 500 words = -3000 characters can decrease my game to ~2 fps

real blaze
#

yeah it could be TMP's text property setter

dull kestrel
#

Text is expensive in comparison to other UI components, but I would not think it would affect you to that extent. That being said, you should never have 500 words on the screen at a time.

novel plinth
#

it shouldn't lag it, even on mobiles

soft moon
novel plinth
dull kestrel
#

That also assumes you also have nothing else on the same canvas updating, as the whole canvas updates.

real blaze
#

hold just a minute. why are u using text setter in the first place?

austere jewel
#

It's also worth noting how they made this

real blaze
#

the validate thing expects a char

soft moon
soft moon
soft moon
# real blaze the validate thing expects a `char`

I have this method too

private char ValidateInput(string text, int index, char c)
{
    if (caretPos == typingText.Count) return '\0';

    string binary = Convert.ToString(c, 2);
    if (binary == "1001" || binary == "1010") return '\0';

    if (c == typingText[caretPos].c) ChangeColor(caretPos, correctColor, CharCheck.Correct);

    else
    {
        if (typingText[caretPos].c != ' ')
        {
            if (c != ' ') ChangeColor(caretPos, incorrectColor, CharCheck.Incorrect);
            else
            {
                if (typingText[caretPos - 1].c == ' ') return '\0';
                else
                {
                    for (int i = caretPos; i < typingText.Count; i++)
                    {
                        if (typingText[i].c == ' ' || i == typingText.Count - 1)
                        {
                            caretPos = i;
                            break;
                        }
                        else ChangeColor(i, incorrectColor, CharCheck.Incorrect);
                    }
                }
            }
        }
        else
        {
            // not more than `maxExtras` extra chars

            int currExtras = 0;

            for (int i = caretPos - 1; i >= 0; i--)
            {
                if (typingText[i].check != CharCheck.Extra) break;
                currExtras += 1;
            }

            if (currExtras < maxExtras)
                typingText.Insert(caretPos, new ColorfulChar(c, extraColor, CharCheck.Extra));
            else
                return '\0';
        }
    }

    ChangeText();
    caretPos += 1;
    return '\0';
}
austere jewel
#

I'm saying they are not using string concetenation and one paragraph with rich text or anything, they are using a custom setup of individual containers each with a single character in it. Presumably for performance and ease of modification reasons

soft moon
real blaze
#

with all the most performant settings.

soft moon
regal lava
#

Maybe try chopping input fields into multiples

real blaze
#

the bottleneck is an internal text generator

regal lava
#

Could be some batching issues

dull kestrel
novel plinth
#

the hangs proly due to ushort limit.. normally it shoulld throw tho

real blaze
dull kestrel
#

But I'm not sure System.Drawing is available in Unity.

soft moon
dull kestrel
#

Kind of

#

You'd have to enable and disable to save performance

soft moon
dull kestrel
#

If you don't that is out of the window.

real blaze
#

@soft moon use the legacy textfield. it ran 16k chars for me without any fuss

regal lava
#

oh man

real blaze
#

but that's it's limit

#

cant go beyond that it seems

regal lava
#

tmpro getting beaten by legacy

dull kestrel
#

The issue with the legacy is that it is less "clear".

real blaze
dull kestrel
#

Yeah, pretty sure TMP is sharper

soft moon
regal lava
#

Is this some render issue? If so, what's wrong with chopping it up and disabling what you're not using?

dull kestrel
#

Have you looked at the new UIDocument etc?

dull kestrel
#

Not sure if that's going to be majorly more performant, but even TMP is aging.

real blaze
soft moon
dull kestrel
real blaze
regal lava
#

legacy actually really fuggly with 3d text

soft moon
regal lava
#

it does get easily pixalted at a distance

soft moon
#

or not as small

soft moon
#
lineHeight = textComponent.GetPreferredValues().y + textComponent.lineSpacing * 
    textComponent.fontSize * .01f;
real blaze
dull kestrel
#

Oddly though Great performance. Since the geometry created by TextMeshPro uses two triangles per character just like Unity’s text components, this improved visual quality and flexibility comes at no additional performance cost.

#

So the fact it has worse performance does make me wonder?

real blaze
dull kestrel
soft moon
#

also I wonder how can it help ??

dull kestrel
# soft moon also I wonder how can it help ??

So if you can calculate the true font's height, you can then multiply it by the line height. If you have a set lineheight, you can (I guess) avoid this entirely.

For web browsers (and I believe UIDocuments but I'd have to double check) you can use em which essentially is all relative (so line-height: 1.3em is like 130% of the font-size). This result * the number of lines, which I believe Font would also allow us to calculate as we can get a width (that we can divide by the maximum width of our UI).

#

That gives us the height of the paragraph. For which we can programmably calculate the offset of the next paragraph.

soft moon
dull kestrel
real blaze
#

@soft moon so about the legacy textField, make sure you don't change the text field...

#

just handle everything by returning a char

soft moon
dull kestrel
#

What are you actually validating?

soft moon
#

that includes Enter, Tab and Space, but does not include Backspace or Delete

real blaze
#

and afaik string is immutable so if you modify it's characters it won't be saved to InputField's text

#

look, the from the Profiler it appears TMP is bad at handling a lot of text at once. so, you can make separate textField per line 🙂

#

then it should work like a charm for infinite amount of lines

#

(just don't use VerticalLayout for them. handle their positions manually)

soft moon
#

there is a problem though

#

lines should be also able to move too

#

so I guess it should be kind of paragraphs

real blaze
#

(to have separate TMP_Textfield per paragraph)

soft moon
#

yes, I should create my own InputField I would say

#

thank you all for help, guys

copper dune
#

Hello,

I'm making a space simulation game, where a rocket has to go from planet to planet using gravity.
Currently, I want to draw the trajectory of the rocket to help the players. I have wrote some code using the Unity's feature Simulate but it doesn't work. The ghostRocketObj used for the drawing doesn't seem to be simulated and just keep its coordonates

Regarless, the game itself runs fine. If I debug ghostRocketObj is used by calculateGravity().

Here's the code used to draw the trajectory:
https://paste.ofcode.org/32CwECBeCkUE99zyAbxeSWy

Here's the code used to calculate gravity using Newton's law:
https://paste.ofcode.org/5QCcMgGFzNXh7pW438QZTE

I feel that's actually not that hard to solve, but at the moment I have to admit that I'm a bit lost. Certainly due to a lack of knowledge of the framework.

orchid lichen
#

i'm currently

setting rendertexture x as active - > making some GL calls on that rendertex - > reading pixels from the current x rendertex into a texture2d - > set previous (normal) rendertex as active - > draw previously assigned texture2d x with a GL using a custom shader

so currently step 3 and 5 are slow af, since i take the rendertex from gpu, pass it to cpu and then back to gpu. i was thinking if there's some way to skip this part and pass the rendertexture straight into the shader without reading it into a texture2d first. that way it'd be gpu > gpu and not gpu > cpu > gpu. any other optimization solutions also welcome. help? thanks

raw lily
#

Is there a reason not to use a ScriptableObject as a normal class, as in creating a bunch at runtime using it's constructor?

dusty wigeon
rancid hinge
#

i'm trying to listen to keys Input in the editor.
it works just fine in the SceneView.duringSceneGui but it breaks in the EditorApplication.update and i have no idea why is this happening atwhatcost , i just want to use Event.current in the EditorUpdate kekwait

using System.Collections.Generic;
using UnityEditor;
using UnityEngine;

[InitializeOnLoad]
public class CollidersBuilderShortcuts : Editor
{
    private static Event currentEvent;

    private delegate void FunctionDelegate();
    private static Dictionary<KeyCode, FunctionDelegate> shortcuts = new Dictionary<KeyCode, FunctionDelegate>() 
    {
        { KeyCode.V, CollidersBuilder.ChangeAxis }
    };

    static CollidersBuilderShortcuts() 
    {
        EditorApplication.update += OnEditorUpdate;
        SceneView.duringSceneGui += OnSceneGUI;
    }

    // i don't get error here
    private static void OnSceneGUI(SceneView sceneView)
    {
        currentEvent = Event.current;

        if (shortcuts.ContainsKey(currentEvent.keyCode))
        {
            shortcuts[currentEvent.keyCode].Invoke();
            currentEvent.Use();
        }
    }

    // i get error here
    private static void OnEditorUpdate()
    {
        currentEvent = Event.current;

        if (shortcuts.ContainsKey(currentEvent.keyCode)) // error is in this line (currentEvent is Null even when i interact with the editor)
        {
            shortcuts[currentEvent.keyCode].Invoke();
            currentEvent.Use();
        }
    }
}

Edit: idk if it's a general question or advanced, but i will put it here anyways.

upbeat path
rancid hinge
real blaze
rancid hinge
#

i made this script:

    private static Event currentEvent;
    private static KeyCode currentlyClickedButton;

    private delegate void FunctionDelegate();
    private static Dictionary<KeyCode, FunctionDelegate> shortcuts = new Dictionary<KeyCode, FunctionDelegate>() 
    {
        // --- Add Shortcuts here ---
        { KeyCode.V, CollidersBuilder.ChangeAxis },
        { KeyCode.B, CollidersBuilder.UndoPoint }
    };

    static CollidersBuilderShortcuts() => SceneView.duringSceneGui += OnSceneGUI;

    private static void OnSceneGUI(SceneView sceneView)
    {

        currentEent = Event.current;

        if (currentEvent.type == EventType.KeyDown && currentlyClickedButton == KeyCode.None && shortcuts.ContainsKey(currentEvent.keyCode))
        {
            shortcuts[currentEvent.keyCode].Invoke();

            currentEvent.Use();
            currentlyClickedButton = currentEvent.keyCode;
        }

        if (currentEvent.type == EventType.KeyUp && currentlyClickedButton != KeyCode.None && currentlyClickedButton == currentEvent.keyCode && shortcuts.ContainsKey(currentlyClickedButton))
        {
            currentEvent.Use();
            currentlyClickedButton = KeyCode.None;
        }
    }

it didn't do what i wanted (i wanted to be able to listen to use input anyware)

then i found this thing: ShortcutAttribute!!!
https://docs.unity3d.com/ScriptReference/ShortcutManagement.ShortcutAttribute.html
that's perfect!!
i will use it instead of my goofy ah script stonks

dusty wigeon
# raw lily Why not?

Mostly because:

  • They behave differently in the Editor and in a Build.
  • You need to manage their life cycle.
#

If you need runtime object, you use POCO (Plain Old C# Object) or Prefab.

severe ermine
#

Don't know what's considered "advanced" but here we go, decided to tackle compute shaders and kind of struggling with something that seems relatively basic. I've got one .compute file that does not have a kernel in it, just a function. I'm trying to call that function from another compute shader using #include "Noise.compute". Adding that line pops off a couple of errors and warnings in the console:

Shader error in 'ChunkGenerator': Did not find shader kernel 'get_3d_perlin_noise' to compile at kernel get_3d_perlin_noise (on d3d11)

Shader warning in 'ChunkGenerator': 'kernel' : unknown pragma ignored at kernel ChunkGenerator at Assets/Scripts/Compute/Noise.compute(1) (on d3d11)

Shader warning in 'ChunkGenerator': 'kernel' : unknown pragma ignored at kernel get_3d_perlin_noise at Assets/Scripts/Compute/Noise.compute(1) (on d3d11)

get_3d_perlin_noise does not exist, I deleted it a while ago, I'm also not sure what it means by unknown pragma ignored at kernel as there is no kernel (probably why it's ignored) in that file, as it just holds a handful of functions

#

I've looked online and can't find much info, compute shaders continue to elude me 😛

misty glade
#

I'm working on my template project in prep for some game jams and prototype work in the year ahead, and want to feel out any solutions y'all might have for the following:

I use enumerations widely in my codebase and have occasionally wanted to view/edit them in the inspector. No problem creating a property drawer there, but I've found that inserting/renumbering my enums causes unity to really shit the bed when I have enums as settings on game objects. Any good solutions for this? I was thinking of hard coding the enumeration values, but this seems like a lot of work over time:

    public enum AudioClipType
    {
        None = 0,
        AlertOneClip = 1,
        AlertTwoClip = 2,
    }
upbeat path
tall ferry
#

removing old values would still mess it up wouldnt it?

misty glade
#

I mean, that's a solution but it's not ideal for some situations. I have one enum for audio clips that I'm roughly sorting by category.. if I just added items to the end wily nilly it would get really hard to read over time

upbeat path
#

yes

tall ferry
misty glade
#

Yeah.. I just realized that this is going to be my only solution because of my desire to start serializing my player database enums by integer instead of string representation.. the database is starting to get large

#

PrimeType, PoseType, AnimationType, CutsceneImageType, OverlayImageType, UnderlayImageType, AudioClip - those are all enums and in the database, string representations

#

I already ran into a document size limitation I didn't know I had because of the large amount of content I was shoving in one document.. and changing from string -> int for enums is probably not going to go well

tribal pivot
misty glade
#

server is unity-agnostic, database is unity-agnostic, so enums is the solution for little bits of data like this

#

like, in the screenshot above, I have this thing called a cutscene that my content creators can edit in the admin tool on the back end - select a background image, play music in the database, etc.. the content gets compressed into a data transfer object, sent to the clients, and then they get to see a cutscene (in unity).. So there's an SO on the client that converts the enum into an AudioClip and plays it when needed

#

I'm not currently linking the enums anywhere in the unity project since that was a disaster - instead I've got a utility function alongside the SO to look up the clip based on enum.. but it's kind of non-optimal since it would be nice to have some prefabs that have clips I could set using the inspector.. currently that's not possible

#

(I do all my audio via code)

dusty wigeon
#

You could use ScriptableObject

misty glade
#

again - the server isn't aware of SO

dusty wigeon
#

That is why you do not separate project.

You might want to use Json then.

scenic forge
#

You can serialize SO in whatever form the server accepts, your runtime representation doesn't have to be the same as its database representation.

misty glade
#

I'm not sure we're speaking the same language. 🙂 I am using JSON, and I am using SOs on the client. 😛 It's ok, it's a little off topic anyway - I was just hoping there were an easier way to manage enums in the unity client if I add/remove them (without serializing/deserializing the string representations)

dusty wigeon
#

Then why do you have an enum that expand with the data you create ?

#

Lets you add a sound for a slash, will you add a value in your enum ?

misty glade
#

Yep.

dusty wigeon
#

Find an alternative.

#

This is terrible

misty glade
#

Why do you think so?

#

Obviously new "content" requires server & client compilation/build, but that's the case anyway since a new sound file needs to be added.

umbral trail
#

is the "enum" a table in the database?

misty glade
#

Having it as an enum (versus a string representation? if that's your proposal) reduces DTO size, database serialization size, has no failed lookups, etc

#

My enums are actual enums in a shared DLL that the server & client (and back office tools) both have access to

dusty wigeon
#
  • Your enum is like 6 page long which make it impossible to select the value you
  • You are using comment in your enum to structure things. That should be already a good give away.
  • You need to modify the enum any times you make a new data.
  • This is specific to your project, meaning that if you ever do an other project, you will need to redo the enum or ignore values.
#

There is probably a milion other issue.

#

You seem to already have a complex architecture, I am pretty sure you can find an alternative.

#

Also, what you do if you have someone on your team that never opened a script and they want to add a new sound ?

granite viper
#

@misty glade This looks like a really good candidate for code generation

misty glade
#

That's not really a pipeline/workflow we support, but it's not one we need either.

#

Hm, that's an idea too mad

misty glade
#

Well, I dunno, we're already in production and it's not been a pain point for us at all? 🤷‍♂️

granite viper
#

You can define your table through a more ergonomic form factor like a scriptable object, and then generate the enum off of that

misty glade
#

I do agree that the large number of sound effect enums is probably not ideal, but it's manageable

umbral trail
#

If the enum values are stored in the database, then the enum should be stored in the database. Then you can just look up the table to get the mapping to integers

granite viper
#

honestly having a giant enum isn't too bad of an option imo, it's just a pain that it's a flat data structure for this use case & unity doesn't have great vanilla support for large enums

misty glade
dusty wigeon
#

I'm just warning you that your 6 pages long enum is not something that I would feel comfortable working with. For me, this is terrible for a lot of reason.

misty glade
tall ferry
#

I couldnt imagine being an intern for this and seeing 6 pages of enums tbh either...

granite viper
#

what kind of db is that?

misty glade
#

Well, the SFX enums are quite big, but most enums are pretty tiny

granite viper
#

custom?

misty glade
#

CosmosDB - it's the MS Azure nosql product

#

Works pretty great tbh

granite viper
#

that should support ints no?

misty glade
#

it does but at the outset of our project we configured it to serialize as strings (in json) because it was easier to debug that way

granite viper
#

ic

umbral trail
#

once you create a table, you should be able to migrate the strings to ints in one or two steps

misty glade
granite viper
#

yeah I wouldn't expect it to be too difficult

#

definitely make a backup ofc

umbral trail
#

if they are strings in the db then what's the problem with the game/server using strings?

misty glade
#

yeah.. it should just work but i'm sort of scared

#

well the problem is more on the unity side

#

I want to be able to both have my cake and eat it to - I use enums for something like AudioClipType in the database, DTO, and client - but Unity doesn't serialize based on the string value, it serializes based on the int value - so I have a prefab and I wanted to say, select an audio clip for "blows up", I couldn't do that in the inspector (well, I could, but if I inserted/changed any enums it would change the value)

#

So instead I have a SO that has a bunch of clips, and a utility library that takes an enum and gets the unity AudioClip it represents

#

ie:

granite viper
#

the default enum drawer is pretty limited

misty glade
#
    public class AudioDatabase : ScriptableObject
    {
        [Space(30), Header("SFX: Alerts")]
        [SerializeField] private AudioClip AlertOneClip;
        [SerializeField] private AudioClip AlertTwoClip;

        [Space(30), Header("MUS")]
        [SerializeField] private AudioClip TrackOneOggClip;
    }

        private AudioClip GetMusicInternal(AudioMusicType type) => type switch
        {
            AudioMusicType.None => null,
            TrackOneOgg => TrackOneOggClip,
            _ => null,
        };
#

something like that

#

it works for me just fine, but obviously with the limitation that using an inspector to edit enum values would not work (unless I manually assigned integer equivalents to the enums and never changed them, which I was hoping to not have to do)

obsidian glade
#

you could parse the enum by string instead on the Unity side - might be awful for performance, but theoretically means the order wont matter

granite viper
#

ok in order to have your cake and eat it, you should be generating your enum and enum values based on some table of truth via code gen. It should be append only, meaning that if old values get removed, that value's number becomes totally invalidated. And then on the other side, you should find/create a more manageable enum drawer that has search

misty glade
misty glade
#

I'm already making it pretty for the admin tool with a utility library that sorts the enums based on .. whatever .. for dropdowns

granite viper
#

@misty glade you could do it with a custom enum drawer, but I think it's better for everything if the int value is the Source of Truth

umbral trail
#

you can make a SO like public class AudioClipID : ScriptableObject { public string Name; public int ID; } and create one for each value in the enum (even better, sync this from the DB). Then to use an audioclip you just use AudioClipID in a field instead of the enum

misty glade
#

some of them need to be alphabetized, some don't, etc

granite viper
#

yah, so that can all be encoded in your drawer and nicely separated from your game code

misty glade
#

there's lots more than just audio clips - like.. here's a snap of the admin tool for cutscenes (all the dropdowns are backed by enums):

umbral trail
#

the db would own the IDs

misty glade
#

(also please don't laugh at my developer art back end.. yes I know it's hideous)

granite viper
#

no it's pretty clean actually

misty glade
#

heh i think it's awful, but it's been two years of bolting on more fields and buttons

#

all the fields are too big, the buttons could probably just be all in one tiny little line, etc.. i'm no blazor/razor expert by any stretch

#

but the end result is the JSON document that the server and client can both consume.. but unity just.. aggravates me a little with the enum thing

granite viper
#

yeah -- im not going to advise you to change your entire workflow, but there's no way around the unity thing. You'll need to code your way out of it

#

code gen is probably the easiest, you can look at unity's new input system for inspiration, since that generates enums for itself as well

misty glade
#

and aside from the string ("sir, we're passing.."), it's very very tiny, both from the data side and networking side

granite viper
#

I appreciate the amount of internal tooling you've done, that's one of my favorite things to develop haha

misty glade
#

all the content is stored on the server so that the content writers can create new cutscenes whenever, without requiring new builds.. obviously new images/sound need new enums which need new builds, but I'm sorta ok with that

misty glade
granite viper
#

what are you paying

misty glade
#

$0! 😛

granite viper
#

haha

misty glade
#

(i'm kidding - we're a tiny studio, too small to hire anyone, constantly going broke etc)

granite viper
#

I'm actually looking, don't get my hopes up like that 😄

misty glade
#

Make you a deal though - download the game, buy a bunch of products, and I'll pay you salary for that much 😉

granite viper
#

lol

umbral trail
#

well, yes, you're going to have to set values in the enum manually and never change them

misty glade
#

how's the joke go? mods are asleep, post nudes job offers

granite viper
#

thus the append-only db scheme

misty glade
#

Yeah.. it's.. OK, I guess.

upbeat path
#

Mods might be asleep but I'm not, so no off topic please guys

misty glade
#

What I'm actually working on is a project template and was hoping to find a better solution to "enum-to-Asset" mapping

umbral trail
#

having an enum stored in a db is a bit iffy though, since the enum is the source of truth for data in the db, and if something happens to it the db data is useless

misty glade
#

I think the "hard-coding" of the integer equivalent as you go with enumeration definition is fine, if a little tedious. The IDE will prevent me from duplicating an ID, and once I create it I can feel free to move it around wherever I'd like - even rename it - and everyone (unity/server/DTO/database) are all fine with it

granite viper
#

yh, code gen would just make that a bit more ergonomic, but that's essentially what you're doing

misty glade
#

Actually, now that I think about it, having the integer tied to the enum is actually more resilient. I had an issue a while ago where I fixed a typo in an enum and shit got broke fast because the database couldn't deserialize the (old) value properly

misty glade
#

and actually looking over my enums file.. yes, I still have sloppy things floating in the pool..

granite viper
#

yeah...

misty glade
#

If I wanted to remove those (unused) enums, it would cause big problems if there's even a single user in the database with that "story bit" (essentially just a floating flag for various one-off things we do)

granite viper
#

I re-assert my suggestion for the append-only local db format

misty glade
#

HashMap<StoryBitType> StoryBits;

misty glade
granite viper
#

(gavel)

misty glade
#

oh I got it 🙂 OK, thanks for the convo all

granite viper
#

👍

soft moon
#

Does anyone know why is _currentEvent's type never MouseDown?

private void LookForEvent()
{
    StartCoroutine(LookForEventCoroutine());

    IEnumerator LookForEventCoroutine()
    {
        yield return _waitForEvent;

        while (Event.PopEvent(_currentEvent))
        {
            print($"type: {_currentEvent.type}; rawType: {_currentEvent.rawType}");
        }

        StartCoroutine(LookForEventCoroutine());
    }
}
#

it just never works when I am pressing my mouse

#

Works just MouseMove while dragging

#

not MouseDrag even

stuck onyx
#

Hello Rider users!

#

Isn't there any funciton/tool to create class diagrams / UML diagrams automatically in Rider? If I remember correctly VS had one,

velvet rock
#

Hey all! I need some guidance on solving a problem.
The problem I am working on in Unity is trying to move a lot of my logic to base C# classes(not their custom MonoBehavior class), and applies to First-Class lists also. I am facing a lot of redundant code, or annoying work arounds.

Solution 1) A custom interface called IWrap, that has a "source" variable that holds the class type that is being wrapped by the MonoBehavior. This is nice because then I can just check if it is a wrapper, and get the base instance and work with that,,, but is also the problem as now I am having to check everything for that. However if I make changes to the base class I don't have to make changes for the wrapper. Kind'a like using a List<> vs a First-Class list(which is ultimately wrapping a list with redundant/unique logic that the end user shouldn't be working with directly).

Solution 2) Is a Has a. If my MonoBehavior implements the interface of the type it is wrapping then I can just call the the methods dirrectly/check for the interface dirrectly. But like with first class lists I now have to pass up every public function I need. If I make any changes to the interface I also have to make the change in the wrappers. Though I can just check for the interface like normal, and don't have to worry about other type checks.

Both are flawed in their own way, and ultimately would like it so they are generated automatically. Not sure what is the best solution, but have looked into stuff like T4, code generation libraries, and weaver(malimbi), or even Rosylin compiler code injection. Anyone work on similar things and have suggestions?

I could get the info for code generation through reflection, and like could make a text editing script that loads in the target script file into a variable and adds code accordingly, but that would be complicated/messy.

velvet rock
#

Like I want it to work like a First-Class class, but have the decoupling of a variable level instance, without having to repeat code everywhere.

flint sage
#

I don't think I fully understand your problem, however the most common approach I've seen to separating logic from Monobehaviour is an event based approach

#

Monobehaviours have a reference to your class and listen to events when state changes and updates the visuals when needed

#

Your business logic does thus not know about monobehaviours at all

velvet rock
#

I do alot of that, but this is more for when you have to interact with MonoBehaviors. Like if the player interacts with an item. You will have to get some component to interact with it. How you interact with it is what I am working on.

flint sage
#

That item monobehaviour can have a reference to the poco class and pass that to the inventory or whatever system you're using

velvet rock
#

Right, which is where my IWrap<> interface comes into play. I get to say I have an instance of this, so just get that and work with it dirrectly. But the problem is now I am having to check for IWrap<MyType> as well as MyType.

#

have an*

flint sage
#

I don't understand why you need that interface

#

You can just have a function on the monobehaviour that returns the data class

velvet rock
#

just in interface form.

flint sage
#

That sounds extra abstraction just to have an abstraction

#

You don't really need it

#

And I feel like it would be a lot less complicated

velvet rock
flint sage
#

Sure

#

But I have very limited information 😛

#

And I have not had the need to have something like that when I worked on similar systems

velvet rock
#

Thank you though

#

For clarification though. The problem with just having a method on a class that returns the instance it is wrapping is I am coupled into that specific class(and if I have multiple classes wrapping it I am having to check for them all). Where an interface that has the specific purpose of having an instance of that type, well now I get them all.

#

But often I am still having to check if it "is a" or "it has a".
if (object is MyType || object.GetType().GetInterface(nameof(MyType)) != null)
As it isn't a first-class type, so I specifically have to look for it, even though it's purpose is to just wrap.

#

The alternative is dirrectly implementing the interface it is wrapping. Which then leads to having to write a wrapping method for every single public method/prop

#
public interface IAmInteractable{
  public void Interact();
}

public class Interactable : IAmInteractable {
  public void Interact(){
    // Do something.
  }
}

public class Interactable_Mono : MonoBehavior, IAmInteractable {
  public IAmInteractable source = new Interactable();

  public void Interact(){
    source.Interact();
  }
}```
#

I want something like

[IWrap(nameof(IAmInteractable))]
public class Interactable_Mono : MonoBehavior { }
#

And for the rest to be generated for me. So any changes on IAmInteractable, don't have to be manually wrapped everytime.

#

I know this is possible, which bringes me back to my question.

#

Both are flawed in their own way, and ultimately would like it so they are generated automatically. Not sure what is the best solution, but have looked into stuff like T4, code generation libraries, weaver(malimbi), or even Rosylin compiler code injection. Anyone work on similar things and have suggestions?

silver lark
#

Hey guys,
Quick question!
Is there a way to set a float array to a material block (so with SetFloatArray), using an offset into the array in question?

Thx a lot!

long ivy
velvet rock
# long ivy this looks like a solution in search of a problem to me. Why is a MonoBehaviour ...

What? I am using IoC in my project, the above code is just an example of the problem. I am not sure how you would handle raycasting out to a gameObject to see if there is an interactable on it. I also have scene level logic on stuff like this that gets the instances through IoC(aka not touching MonoBehaviors). But for specific instances where I need to interact with MonoBehaviors.

velvet rock
#

If it was all internal code I could just only use IWrap<>, but it isn't so I am having to check for the Interfaces themselves also, as IWrap isn't a first-class instance.

#

which brings me back to the question of
Both are flawed in their own way, and ultimately would like it so they are generated automatically. Not sure what is the best solution, but have looked into stuff like T4, code generation libraries, weaver(malimbi), or even Rosylin compiler code injection. Anyone work on similar things and have suggestions?

#

To be fair adding IWrap check is a lot shorter, and decoupled then implementing the interface directly, but I am still having to check for something who's whole purpose is just to use it directly. Were through code generation I can just use it directly without the hassle of writing the boilerplate code.

#

If y'all are happy doing those good for you, but there is a better way.

long ivy
#

you are adding an unnecessary layer of abstraction based on my reading. It looks like, for all intents and purposes, your interface implementations are Components. You are trying to hide this detail by moving it into POCO objects, except they still have that dependency on MonoBehaviours so they're tightly coupled anyway

velvet rock
#

Take an item. In most usecases it is tied to the MonoBehavior itself, and the object it is on. But I look at that as just the representation for the player. If I had a player go into a shop they would have to click on the item(as there is no way for them to move the class dirrectly in RAM). However take an AI, if I have an AI go into a shop, they don't need to walk up to the item and click it, they just need the instance of the item, and let what ever is incharge of the shops in game representation remove the graphic representation. Which is where IoC come into play and alot of layers most Unity programers never use. I do, and instead of sitting here for a month explaining why I am 100% this is a problem, I just ask the next person to not reply with a doubt, but advice or experience.

#

Also note I am using an Item as an example as it is simple. I have alot more complex interactions this is needed for that I do not have time to write out, let alone explain.

#

Also I should say the graphic logic is separate from the class logic, but somewhere it has to tie together/get passed around.

glacial wedge
#

What is more efficient? collider.ClosestPoint vs collider.ClosestPointOnBounds
My closest point will be onbounds because the confronting point is out the collider

velvet rock
#

This is programing my dude

tired elbow
#

If I'm trying to use an external C++ library, is it best to reference its functions directly or to create my own C++ library "A" where I reference the functions of the external library "B" I need and then reference "A" in Unity?

tired elbow
#

I'm confused about how to go about this, I can't seem to find any good references on how to reference existing C++ libraries

#

also if the functions aren't directly made to support this feature, then the method names turn up mangled.

velvet rock
#

Okay, so I am not crazy 😆 .
I believe this has to be a common use case for Microsoft's new Source Generators, and is even listed as a use case in the Roslyn Source Generator Cookbook, but with no example implementation.

#

I would love Unity to support partials and MonoBehaviors, but just gonna stick with figuring it out for single life classes for now.

dusty wigeon
velvet rock
#

Dang it, just imagine the you sure about that meme. partials on MonoBehavior classes are not supported, normal class yes.

velvet rock
dusty wigeon
#

Friend, I have a partial on a MonoBehaviour.

public abstract partial class Character : AdvancedNetworkBehaviour, IDamageable, IHaveStats, ISkeleton
public abstract class AdvancedNetworkBehaviour : NetworkBehaviour
public abstract class NetworkBehaviour : MonoBehaviour

velvet rock
#

I am not sure what you were trying to show there.

dusty wigeon
#

That you can do partial on class that inherit MonoBehaviour

velvet rock
#

Oh wait I see it

#

I tested dirrectly(aka not inherited/abstract). So that indeed could be a work around I wasn't familiar with.

#

On just a plain MonoBehavior the other partial wasn't getting serialized to my memory(or something along those lines I would have to test again).

dusty wigeon
#

I have no serialize data in the other, that I can say.

dusty wigeon
#

Anyway, like the other said, you are over abstracting things.

#

What is the reason why you want to divide Unity and your logic.

velvet rock
velvet rock
dusty wigeon
velvet rock
dusty wigeon
#

Just use correct OOP pattern and architecture.

velvet rock
#

XD oh man. You are using them wrong if you don't like them.

velvet rock
#

which, from the number of layers of abstraction I can see your dislike.

#

I work in C# libraries with them all the time, and it is great for code cleanliness(if done right, but can go wrong quickly).

#

Also a MonoBehavior inside a MonoBehavior "works" but the inspectors name of it is broken.

tired elbow
# dusty wigeon No...

They are great for accessing private non-serializable members of monobehaviours within a custom inspector

soft moon
#

Does anyone know why pressing Tab also executes this part of code: print($"character: \"{c}\"");?
That should return though.

private void KeyDownEvent(Event evt)
{
    switch (evt.keyCode)
    {
        case KeyCode.Backspace:
            print("Backspace");
            return;

        case KeyCode.Delete:
            print("Delete");
            return;

        case KeyCode.Tab:
            print("Tab");
            return;
    }

    char c = evt.character;

    print($"character: \"{c}\"");
}
orchid marsh
dusty wigeon
soft moon
orchid marsh
#

If visibility is an issue, print the enum value

#

Also, hopefully the key code and character are representatively the same.

#

When illustrating issues like this, you ought to show the console tab as well so that we can verify what you've visually seen.

dusty wigeon
soft moon
#

that should finish void method, shouldn't it?

orchid marsh
#

If the return statement was met, the remainder would not have happened.

soft moon
#

that's why I ask

orchid marsh
#

Likely two instances of that function where the second didn't qualify for premature returns.

#

Where keycode and character aren't the same.

orchid marsh
#

Print both before the switch.

#

The return statement will cause the remaining statements inside the function to not have occurred.

#

This is well defined.

soft moon
orchid marsh
#

The return never happened then.

tired elbow
orchid marsh
#

Two instances of the function.

#

One enters the switch case. The other does not.

soft moon
orchid marsh
#

You'll get two prints.

#

Simple as that.

#

A return statement will ignore the remainder of the function.

soft moon
soft moon
#

yes, let me debug

orchid marsh
soft moon
#

there is written "1 reference"

orchid marsh
#

I wouldn't know. I just know that return would escape the function prematurely.

soft moon
orchid marsh
#

Who knows, but it's certain that the switch statement has been tested twice. The first had a matching case. The second did not.

#

Print the key codes and characters before the switch statement.

#

An easy test would be printing hello before the switch

soft moon
#

yes, I have debugged, it's called 2 times, hold on

orchid marsh
#

It should print twice

soft moon
#
using UnityEngine;
using UnityEngine.UI;
using System.Collections;

namespace TMPro
{
    [RequireComponent(typeof(Image))]
    [AddComponentMenu("TypingField", 1)]

    public class TypingField : Selectable
    {
        #region Fields

        [SerializeField] private TMP_Text m_textComponent;

        private Event _currentEvent = new Event();

        #endregion


        private void OnGUI()
        {
            Event evt = Event.current;

            if (evt != null)
                CheckEventType(evt); // here
        }

        private void CheckEventType(Event evt)
        {
            switch (evt.type)
            {
                case EventType.KeyDown:
                    KeyDownEvent(evt);
                    break;
            }
        }

        private void KeyDownEvent(Event evt)
        {
            print($"character (1st): \"{evt.character}\"");

            switch (evt.keyCode)
            {
                case KeyCode.Backspace:
                    print("Backspace");
                    return;

                case KeyCode.Delete:
                    print("Delete");
                    return;

                case KeyCode.Tab:
                    print("Tab");
                    return;
            }

            char c = evt.character;

            print($"character: \"{c}\"");
        }
    }
}
orchid marsh
soft moon
#

frames in OnGUI():

  1. called and printed Tab
  2. skipped, cause case EventType.KeyDown: if false
  3. called and printed $"character: \"{c}\"", cause KeyCode = None, but evt.character = \t
orchid marsh
#

Mystery solved

soft moon
brisk stone
#

I want to make a spider with kinematic animations where only the body moves in a straight lines and the legs will follow it. The spider will move on the background ( I have a side view game using tilemap ) Any tutorials available that will help me do this? I understand how it works but I have a hard time actually implementing it. I want to implement it myself more than I want to use a package already implemented, but as a backup a package is welcomed as well

orchid marsh
#

Have a parent and two children. The parent moves and children follow. One child being the spider body. The other being the legs. They're now decoupled but share a base parental movement. Freely allowing them to offset, modify or have independent movement behaviors from one another. Assuming you just want the legs to not precisely follow the body but still be attached to the whole.

brisk stone
#

So basically I don't move the body. I move the parent object and the body, which is a child, will follow it? The legs will also follow the parent object but with an offset? I can see that working, Thanks!

velvet rock
#

Or document if I figure out a better way and why later. For example I made two seperate IoC libraries to meet specific needs no other one filled. The first one used reflection, and all though very feature rich added to much complexity/performance impact. So the second one had all the lessions I learned from the first.

dusty wigeon
velvet rock
#

Oh no which parts/how it violates Liskov principle

dusty wigeon
#

Liskov principle is about implicit contract between object. It explain that relation between object are semantic and not only syntaxic.

#

In other words, in your case, you are abstracting the whole UnityEngine (syntaxic), but you will definitily not be able to define correctly implicit contract.

#

An implicit contract can be something such as, this most be performant, this most release resource after use, this most be setup before usage etc.

#

If you were to replace the UnityEngine, you would have an inconsumerable amount of error due to all those small implicit contract that cannot be respected.

velvet rock
#

Ah, alot of that I am defining before hand through IoC, and wrappers around Unity specific(but not game engine specific) logic.

dusty wigeon
#

The usage of MonoBehaviour can be one of those implicit contract.

#

You might, and will, probably depends on how Unity handle MonoBehaviour.

scenic forge
#

Are we still talking about partial classes?

dusty wigeon
#

Liskov principle

scenic forge
#

Ah.

velvet rock
velvet rock
scenic forge
#

(Well FWIW, partial classes should really be used only by source generators. Wanting to use partial classes for code organization purposes is mostly a symptom of underlying problems. And obviously they are also not ergonomic to use in IDE, it makes navigating so much harder.)

velvet rock
# scenic forge (Well FWIW, partial classes should really be used only by source generators. Wan...

I found that at first also. But how I use them is very specific. For example the IoC system I made uses them, the main logic for the IoC is in the main file, it contains the Interfaces being used, and then in the partial classes I encapsulate the reference to the functionality(often as a variable of the sub interface type), and the default implementation of logic after.

IoC.cs
public interface IoCLogic {
  public IRegistering registering;
}

public partial class IoC : IoCLogic {
  // Base stuff
}
IoC.Registering.cs
public interface IRegistering {
  public void MyFunctionality();
}

public partial class IoC {
  public IRegistering registering;
}

public class IoC_Registering_Default : IRegistering {
  public void MyFunctionality() {
    // My default logic.
  }
}

Not my actual code, just an example.

#

Which allows you to jump to the logic from the interface reference.

#

Easy navigation. Though resharper also helps a lot.

#

Now if you want to work on the main functionality of the class you don't have to worry about any related, but distinct logic. Like wise if you need to work on the Registering logic you don't have to worry about the other ones. Also is a life saver with version control.

#

I have found using partials can easily be abused though.

orchid marsh
#

What's the purpose of this? What does it solve? Is it simply a boiler plate to eliminate having to understand the API or does it serve some other function? I wasn't here from the very beginning so I may be missing some important key points.

velvet rock
# orchid marsh What's the purpose of this? What does it solve? Is it simply a boiler plate to e...

For me and my project, it is to keep close but destinct logic seperate, while also keeping a good connection to base implementations of that logic. For example the IoC would be like 1k lines, but now I have 5 200 line files. How the interface is setup allows for you to switch-out that logic easily. Again, just one mans solution to problems I have faced, not claiming it to be the best. Just what works for me so far.

#

As if one branch needs a fix to Registering, and another needs a change to Scope setup, I now don't have to worry about conflicts in version control.

quartz pagoda
#

Watching a tutorial on coroutines. Isn't this eventually going to cause a stack overflow?

tiny pewter
#

maybe the unity engine internally kill the caller coroutine since there is not any yield after the startcoroutine function call

regal lava
#

Are you watching a tutorial on how to crash your editor

upbeat path
severe topaz
#

why not use while loop for that, though?

regal lava
#

I've had situations where the editor would discard coroutine operations if too many operations are being applied. Creating some bad while loops on the other hand is instant crash though.

tiny pewter
#

if you dont yield return in dead loop then the editor freezes...

upbeat path
#

if you dont yield, it wont compile

quartz pagoda
#

ok another question..

#

i construct a mono behaviour through an installer without a game object attached to it:

#
            this.Container
                .Bind<WallBehaviour>()
                .FromNewComponentOnNewGameObject()
                .AsSingle()
                .NonLazy();
#

then inside this mono behaviour im trying to start a coroutine but apparently the newly created game object has to be manually marked as active first

#
public class WallBehaviour : MonoBehaviour
    {
        private const float DistanceBetweenTiles = TileWidth / 2.0f; 
        private const float TileColumnCount = 17.0f;
        private const float TileHeight = 0.026f;
        private const float TileWidth = 0.019f;

        private WallPartBehaviour.Factory _wallPartBehaviourFactory;
        
        [Inject]
        public void Construct(WallPartBehaviour.Factory wallPartBehaviourFactory)
        {
            this._wallPartBehaviourFactory = wallPartBehaviourFactory;
            this.gameObject.SetActive(true);
            this.StartCoroutine(this.ConstructWallPartsCoroutine());
        }

        private IEnumerator ConstructWallPartsCoroutine()
        {
            for (var i = 0; i < 4; i++)
            {
                var wallPartBehaviour = _wallPartBehaviourFactory.Create();

                wallPartBehaviour.transform.SetParent(this.transform);
                wallPartBehaviour.transform.RotateAround(Vector3.zero, Vector3.up, i * 90.0f);
                wallPartBehaviour.transform.Translate(0, 0,-(DistanceBetweenTiles / 2.0f + TileHeight / 2.0f + TileColumnCount * TileWidth / 2.0f));

                yield return new WaitForSeconds(1.0f);
            }
        }
    }
#

is this expected behavior? or am i doing something wrong?

#

im not sure i understand what being active means

tiny pewter
#

what is the return type of _wallPartBehaviourFactory.Create()
i remember you cannot new Monobehaviour

quartz pagoda
#

it is a monobehaviour. but its a factory method

#
        [SuppressMessage("ReSharper", "ClassNeverInstantiated.Global")]
        public class Factory : PlaceholderFactory<WallPartBehaviour>
        {
        }
#

its a pattern recommended in the zenject docs

#

the PlaceholderFactory is a zenject class that provides the Create() method

#

but i had to mark the WallBehaviour as active (the mono behaviour which the coroutine belongs to) not WallPartBehaviour

#

i dont fully understand the consequences of this or if its the most concise way to do it

#

is there a reason the new game object which is constructed by the installer is not active by default?

#

i understand this is more a zenject question than a unity question...

tired elbow
umbral trail
#

if you just want to reference exported functions from a dll you need DllImport, check the docs on that

soft moon
#

Maybe, someone has worked with TMP a bit and could help me out.
Here I (easy to understand from method) set custom caret's position to the end of last line (currectly used actually), but it gonna by always last one anyway.
When pressing Space button (char = ' '), caret is moved not enough right. Like 20% of needed. Then when I do press next character, caret moves those 80% left and 100% more (to next character's position).
How do I fix it?

private void SetCaretToEndOfLastLine()
{
    TMP_TextInfo textInfo = textComponent.textInfo;

    if (textInfo.lineCount > 0)
    {
        TMP_LineInfo currentLine = textInfo.lineInfo[textInfo.lineCount - 1];

        TMP_CharacterInfo charInfo = textInfo.characterInfo[currentLine.lastCharacterIndex];

        Extents extents = currentLine.lineExtents;

        float middleX = text.Length > 0 ? charInfo.bottomRight.x : charInfo.bottomLeft.x;
        float middleY = (extents.min.y + extents.max.y) / 2f;

        caret.position = textComponent.transform.TransformPoint(new(middleX, middleY));
    }
}
sand shore
#

I cant test it right now but it should work

misty glade
#

Convention check: Do you namespace like CompanyName.ProductName or CompanyName.ProductName.SomethingElse?

I'm looking back on my codebase and I don't really see any reason to have broken down the namespace buckets like I have - if anything it's just been more of an extra step of boilerplate. I can't think of any really good reasons (within the Unity project) to break down namespacing any further.

Thoughts?

granite viper
#

it's a personal choice

#

for myself, I tend to only break up namespaces further if it's a sufficiently different thing that I want to be silo'd from everything else

mystic flume
#

Maybe for large systems

misty glade
#

Yah I mean, my system is "large" already (150k lines of C#, 5 separate projects) but I still regret the namespace stuff I subjected myself to

#

i end up with files that look like that

mystic flume
#

I mean i'd give individual large systems their own namespaces

#

But not really modules inside the system

misty glade
#

yeah, I think that's the way

#

I probably could have a namespace for each of my 5 projects, only one of which is the unity one

#

Unity, Shared, Server, Admin and Bots - and then all of my unity files would just have one using for the shared DLL

#

instead of the garbage above

mystic flume
#

Yeah that could work. Though it's not that uncommon to see large using areas like you have there, reminds me of working on large C++ projects and the 100 lines of #includes at the top haha

misty glade
#

It'd be fine if I could use global using (I seem to recall it's a newer c# lang feature but I can't keep track of which features come in which c# versions)

mystic flume
#

Yeah you can define some kind of global usings file... never done it before though

misty glade
#

I do, but not in the unity project.. the server project which i believe I'm using c# .. 9?

#

c# 10 it seems

harsh perch
#

hey how can I connect to a mongodb database securely from my game, I don't want people to easily access it by decompiling the game

#

needs to have write access

tall ferry
harsh perch
#

online leaderboard for best time

tall ferry
#

if the information is sent by local games, there isnt anything you can really do about this besides try to verify that the files have not been changed. Even then, there will be workarounds for those truly motivated

harsh perch
#

hmm

tall ferry
#

For example, if your concern is just people decompiling, seeing the database info and pushing their own score, you can try to prevent this but whats gonna stop someone from just modifying how the score is obtained then sending it legitimately through your system

harsh perch
#

oh yeah true

#

i'm more worried about people just deleting the whole database

tall ferry
#

when you setup your database, you will have the option so people cannot randomly delete. I have not used mongo specifically, but id assume it has this option

harsh perch
#

yeah but why not just fetch all documents and delete them individually

tall ferry
#

you just make a seperate user/role if you need to delete entries, or just do it manually yourself if its not a major concern

harsh perch
#

find all documents, delete each document in for loop

#

or entries, same thing

tall ferry
#

i dont get what you are trying to say, your database will 100% have "roles" or something similar so users can only do what you let them

#

how deletion is handled is irrelevant, because they wont have delete perms at all

#

if your database doesnt have roles or anything similar, swap to a new database

harsh perch
#

oh alright

tall ferry
#

although im sure mongo has, i just never used it

harsh perch
#

wouldn't you be able to set everyone elses time to 0 or something

tall ferry
#

have u used databases by chance before?

harsh perch
#

yeah, but not inside a client

#

only I had direct access

#

it was in discord bots before

tall ferry
#

updating an entry should be a separate role from inserting entries

harsh perch
#

what if you beat your time though

#

then there would be multiple documents?

tall ferry
#

if you want one person to have 1 entry max, then you will need some other authority to verify who they are before updating the info. Maybe like a steam login

harsh perch
#

I was thinking discord, but okay

#

not ready to spend $100 for a steam page

tall ferry
#

if you can properly link your game to discord login, i could see how it would work

harsh perch
#

alright

#

so verify login before changing data

tall ferry
#

I honestly dont know how you'll verify it at all with discord

harsh perch
#

hmm

tall ferry
#

you could try linking it to email even, might be easier

#

at the end of the day you're still gonna need some system to act like a login system. This might be way too overkill instead of just allowing users to have multiple entries

harsh perch
#

sorry, how would that prevent people from hacking my database?

tall ferry
#

🤔 the permissions are what would stop people from "hacking" it

#

again, theres really not much you can do about people modifying how the score is obtained unless you are able to verify files were not changed

harsh perch
#

do you mean each person would have their own mongodb account

#

or

#

inside the database, that is

tall ferry
#

thats not what i was saying. i was just saying if you want people to be able to overwrite their own entry, you need a way to verify who they are. Either way though this is likely overkill for your project unless you think this will have a massive audience

#

really you should experiment with permissions first before worrying about anything else

harsh perch
#

ok

soft moon
#
// float middleX = text.Length > 0 ? charInfo.bottomRight.x : charInfo.bottomLeft.x;

float middleX = charInfo.topRight.x;
#

seems like I should discover unity's source scripts to find it out UnityChanDown

sudden spruce
#

I have this shoulder weapon in a 2D game that I want to detach and have shoot independently. What would the best way to go about this be?
Its currently animated for basic movement but should I remove it from the sprite and have it procedurally attached?

granite viper
#

should I remove it from the sprite and have it procedurally attached?
basically yes

sudden spruce
#

down the procedural animation rabbit hole I go

granite viper
#

you don't need to do it procedurally, you could animate an anchor point with the base animation

#

and then track the gun onto that

devout coyote
#

But their tokens do not contain any data

#

You still need to create your own backend for more proper tokens

#

Or everytime a user requests you get their user information and only allow them to edit their own record that way

glacial wedge
#

using a raycast inside a collider that doesn't hit the collider bound hit the collider?

nocturne osprey
#

is there a way to create AvatarMask in code ? I have an Animator without an Avatar ( The creature was created with primitives and nested together )

#

im playing animations using Animator.Play( string )

#

and im creating them inside the editor itself using the record button

#

but idk if i can play two animations in the same time , or if i can create AvatarMask for the structure that i have created

brave cairn
gleaming rock
#

Is there any sync tool to sync at least C# scripts between 2 folders?
I am making multiplayer game and would help out a lot if I could modify some definition on server and would change on client project too.

I know there is at least Link & Sync but it is buggy and doesn't always sync the files. It would be useful it it could also sync things like scriptable objects and their references.

nocturne osprey
#

thanks for the info btw

dusty wigeon
gleaming rock
dusty wigeon
brave cairn
gleaming rock
gleaming rock
dusty wigeon
# gleaming rock Why?

Because, it is the easiest way to keep both project sync. Otherwise, you gonna have a lot of issue. Also, most Multiplayer API in Unity does not support multiple project, and for a good reason.

brave cairn
gleaming rock
dusty wigeon
#

At the end, you do you. I'm only saying what from what I have experienced work the best.

brave cairn
#

You already facing syncronization issues btw (by searching replication tool)

gleaming rock
#

I mainly need to sync scriptable objects and C# scripts (theres like 50 of them)
I need 2 separate projects because my project follows client---dedicated server model = there is no sense in having just a single project for both, the server does all server calculations and server networking
while the client is used to play the game and connect to the server

ancient solstice
#

You can absolutely have that in one project. You have dedicated server & normal client build targets and can exclude code run on one side only by using preprocessor defines for example.
That's what I do.

dawn zephyr
#

hey guys, i need to have 20 gameobjects of class A and to initialize them, would it be better to have them all in the scene in an array, iterate through it and initialize only the 20 i need OR just instantiate these 20 and initalize right after the instantiation, in terms of gc, loading times etc..

dusty wigeon
# gleaming rock I mainly need to sync scriptable objects and C# scripts (theres like 50 of them)...

50 Scripts and Scriptable Object is nothing.
It is not because you have client --- dedicated server model that you cannot make a single project. You use precompiled instruction, assembly definition and well structed architecture/folder to make everything works together smoothly. (Whenever you ship at the end, your client will be your client and your server will be your server) I am doing that, with exactly a client---dedicated server model in a production with significative amount of player.

dusty wigeon
dawn zephyr
#

how come?

dusty wigeon
dawn zephyr
#

how does the scene load? doesnt it instantiate there too?

dusty wigeon
nocturne osprey
#

now i need to figure out how to generate it with code and save as an asset so it can be linked inside the animator

#

( im guessing editor hacks are needed to manually set avatarMask object to a layer at runtime ? )

dusty wigeon
nocturne osprey
#

Cannot create avatar or mask , is there a walk around this somehow ?

var avatar = AvatarBuilder.BuildGenericAvatar( target.gameObject, string.Empty );
AssetDatabase.CreateAsset( avatar , "Avatar.asset");
AssetDatabase.SaveAssets();
Selection.activeObject = avatar;
var asset = new AvatarMask();
foreach (var t in targets) asset.AddTransformPath(t);
AssetDatabase.CreateAsset(asset, maskName + ".mask");
AssetDatabase.SaveAssets();
Selection.activeObject = asset;
#
UnityEngine.StackTraceUtility:ExtractStackTrace ()
AnimMaskBuilder:OnValidate () (at Assets/Ragdoll/AnimMaskBuilder.cs:19)
UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&)```
nocturne osprey
#

i figured out how to create the avatar asset

#

the extension was .ht

#

and the name property must been popluated

#

but its empty

#

whenever i try to set the avatar as a reference inside a new avatar mask , nothing shows up

#

oddly enough when i open the ht file in a text editor it looks like it did capture the data

novel plinth
#

try to refresh your assetdatabase

#

right after you save it

nocturne osprey
#

still the same

nocturne osprey
#

tried extracting type of Avatar from an importex FBX file , and now untiy gives me the following message:

var objects = UnityEditor.AssetDatabase.LoadAllAssetsAtPath(assetPath);
for (int objectIndex = 0; objectIndex < objects.Length; ++objectIndex)
{
  UnityEngine.Object currentObject = objects[objectIndex];
  if( currentObject is Avatar )
  {
    Debug.Log( "Extracting: " + UnityEditor.AssetDatabase.ExtractAsset( currentObject, "Assets/ExtractedAvatar.ht" ) );
    UnityEditor.AssetDatabase.SaveAssets();
    UnityEditor.AssetDatabase.Refresh();

  }
}
// 
> Extracting: The importer FBXImporter must support remapping of sub-assets of type Avatar
#

so basically i can't open it in a text editor to compare it and see why the created asset with BuildGenericAvatar doesn't show transforms in the inspector ...

#

i just need a way to filter animations ... wouldn't mind using two animators if possible

vital ibex
#

Is there an issue using VisualEffects with ScriptableObjects? I'm trying to reference a visual effect prefab from a SO property, and I have it set on one instance of the SO but if I try to set it on another instance I can't see it in the Assets list unless I open the prefab in the scene editor, and when I set the reference from there, the field shows Type Mismatch

dawn zephyr
#

Can anyone help me figure out why does this upload to my firebase database as {}? I know for sure the array isnt empty
public async UniTaskVoid SetValueToDatabase(string path, object value) => await _databaseReference.Child(path).SetValueAsync(value);

    {
        CageStats[] statsToDatabase = new CageStats[_cagesCollection.Count];
        for (int i = 0; i < _cagesCollection.Count; i++)
        {
            statsToDatabase[i] = new(_allCages[i].CatSpecie, _allCages[i].ActiveCats, _allCages[i].SecondsLeft);
        }
        string json = JsonUtility.ToJson(statsToDatabase);
        DatabaseManager.Instance.SetValueToDatabase("Cats", json).Forget();
        print(statsToDatabase.Length);
    }```
#

also CageStats has the [Serializable] attribute, I already managed to save this struct, the problem has to do with the array for sure

sly grove
#

probably JsonUtility.ToJson is producing {}

#

in fact it's obvious why

#

because JsonUtility does not support naked arrays

#

JsonUtility only supports objects as the root JSON element

dawn zephyr
#

fk chatgpt fr he said it supports arrays and objects

#

so how could i store a collection of structs with json then or cant i

#

maybe ill just wrap it in a class? idk

sly grove
sly grove
dusty wigeon
#

You just have to wrap your array dont you ?

sly grove
#

it supports arrays just not naked arrays

dawn zephyr
#

so boxing works?

sly grove
#
[Serializable]
public struct MyWrapper {
  public MyType[] arr;
}```
#

this will serialize

#

as long as MyType is serializable

dawn zephyr
regal olive
#

Hey everyone. When I play my game in the editor everything seems ok, but when I try to play standlone versione - suddenly field of view is different. I do not change field of view in any of my scripts, I use URP and camera stacking. I checked if it does the same with builtin render pipeline and yes, it does. Any ideas?

sly grove
#

in other words - FOV determines the vertical visible viewing angle, and the horizontal is dependent on the aspect ratio, which may be different in your fullscreen build vs the editor window

sand shore
# soft moon nope, it doesn't work 🙄

Update your line where you set the caret position to use Vector3 and if that still doesn't work you can try to calculate the position using the line's extents:
float middleX = extents.max.x;

and set the carets position using Vector3:
Vector3 caretPosition = textComponent.transform.TransformPoint(new Vector3(middleX, middleY, 0f));
caret.position = caretPosition;

soft moon
#

Vector3 does not play any role, cause new Vector2(middleX, middleY)'s z position is still 0f

#

and it doesn't work too

#

extents just do not react to Space (' ') character

#

also it writes that width of default character is 14.91293 and of Space is 1.071411

#

check with

float width = charInfo.bottomRight.x - charInfo.bottomLeft.x;
sand shore
#

You could try to calculate it using the bounds of the last character:
Bounds charBounds = charInfo.bounds;
float middleX = charBounds.max.x;

#

If this doesn't work then I don't know whats wrong with it. The way I usually fix my errors is that I just try every different solutions I can think of until it works

soft moon
#

TMP_CharacterInfo does not contain a definition for bounds

soft moon
#

not succeded yet

#

space character is just smaller than other, but when other character is pressed - it becomes bigger

#

and I do not know why

#

that's extremely strance

sand shore
#

Yeah I dont know why that happens

soft moon
soft moon
#

@sand shore
I have solved the issue by debugging TMP_CharacterInfo class and writing just in case you are interested.

Correct middleX position is:
We need to get character's xAdvance to make space work normaly

// float middleX = extents.max.x; // Space does not work here

float middleX = charInfo.xAdvance; // takes all the characters into account

The xAdvance property in TMP_CharacterInfo represents the horizontal advance width of a character. It indicates the amount of horizontal space the character occupies when rendered within a text element.

misty glade
#

What's your workflow for imported UI packages? Do you bring them into an import project and copy and paste the prefabs/textures/scripts over to your working project? Or do you just yolo them and import them into whatever directory the asset author created and let unity build the assets out of the release?

dusty wigeon
gloomy mica
#

Hi guys I got a managed memory profiler problem here. Unity profiler memory module & some 3rd party tool both reports a Mono memory of ~230MB, but the Memory Profiler package said managed objects total size is 133.5MB, why the difference? Are there any other stuff in the managed heap besides all managed objects?

#

I am using Unity2018.4 and Memory Profiler Package preview v0.2, and I'm profiling android phone ,not the editor

flint sage
#

One guess is that one of them reports actual used memory and the other reports reserved memory

gloomy mica
#

I don't think so, the built-in profiler reports both used and reserved memory of > 200MB

dusty wigeon
#

(And yes, we had fragmentation issue that is now solved)

regal olive
gloomy mica
gloomy mica
#

(as for memory optimization, my game cost too much memory)

dusty wigeon
gloomy mica
#

but right now I can't see the details of that 130M

dusty wigeon
#

However, I feel like you original memory is too high overall.

#

Fragmentation should drop as you optimize.

#

If I am correct, you should expect fragmentation to be as high as 40%-50% of your memory consumption.

#

If it augments linearly with the amount of reload/update, then you have an issue. You might be doing large allocation but only preserving a small part of each frame/update.

gloomy mica
#

is memory fragments included in the used memory value, or is it the value of (reserved memory - used memory)?

gloomy mica
#

ok thank you sir

devout coyote
#

Relatable

bleak citrus
#

"why is the game running so terribly? i only have five characters in the scene..."

dawn zephyr
#
    private async UniTaskVoid LoadReachedRegion()
    {
        DataSnapshot catsSnapshot = await DatabaseManager.Instance.GetValueFromDatabase("Region");
        ReachedRegion = (byte)catsSnapshot.Value;
    }```
```    public async UniTask<DataSnapshot> GetValueFromDatabase(string path) => await _databaseReference.Child(path).GetValueAsync();```
anyone mind telling me how would i go about implementing this? getting a number out of my firebase database? without using json, also, any suggestion to improve or any feedback would be very welcome im quite new at this firebase thing
remote drift
#

Is coroutine iteration API exposed in any way?
For example I want to use all built in enumerators like seconds skipping and etc. But run MoveNext by myself

dull raft
misty glade
#

Blue sky-ing out the architecture for a new multiplayer game, and I'm thinking I want something more resilient than my last approach (containerized headless c# console app, kept game state in memory and wrote changes to the database periodically and on client connect/disconnect). Clients connect via a TCPIP socket and maintain the connection during gameplay - but typically only need to send messages to the server every 20-30 seconds during active gameplay (ie, it's not a FPS or anything that requires fast responses/reflexes).

The downsides of the above were that all users had to be on one shard, and the console app wasn't great at talking to the Blazor/Razor admin tools and vice versa (ie, if you wanted to edit a player with the admin tools, you could only edit the database, meaning if a player was online there were issues). Additionally, scaling is difficult since everyone's playing on one container - the app can scale to several thousand CCUs but it's still a bottleneck that I'll need to address in the future.

I'm wanting to do an MMORPG (with enough experience to know what I'm getting into) and wondering if I should go to something different. I don't think a restful API would be useable here, but maybe I could handle a restful API for things like "slow actions", some sort of multicast server for chat, and then various containers for various zones where people would disconnect/connect fluidly as they traveled around.

Looking for any high level thoughts on architecture or unity considerations, specifically with respect to networking, concurrency, and scalability. TBH the networking stack I built for my last app worked pretty well from the Unity side - it's just more the server/database/admin side that was.. painful.

My experience/stack is currently with Protobuf, MessagePack, MS Azure for everything cloud based (CosmosDB for data, Docker containers for server shards, Blazor/Razor for back office), Telepathy for networking and uh.. a bunch of other stuff. 🙂

granite viper
#

@misty glade this series comes recommended and goes down the line on everything you need for mmorpg

glass hill
#

When you CreateInstance on a ScriptableObject
Are those instances located somewhere?

dusty wigeon
plush hare
#

"but typically only need to send messages to the server every 20-30". Is problematic if you're actually going for a real mmorpg.

glass hill
#

I know that, I just meant like are runtime assets ever placed in Resources, etc.

#

But I figure not. i found a workaround for what I needed

pure dock
sly grove
#

Through something like Asset database.CreateAsset

#

Which doesn't even exist in builds anyway

glass hill
#

I figured. Just had to ask. Thanks.

green pagoda
#

Which is the best Online Course to learn C# for unity from beginner to Advance ???

severe topaz
misty glade
misty glade
#

I do think that a stateful server or containers segmented either by service (chat/lobby/battle/social) or location (zones/levels/etc) is probably going to be best, though, since a restful server farm is going to be an incredible load on the database since every request will essentially be stateless. Also, it gets difficult to push data out to clients - they'll have to poll for it which is... annoying and probably will just end up creating a lot of unnecessary churn. Sure, it'll scale easier since I could just throw more instances at it, but it'll be way more resource intensive as a whole.

plush hare
#

That's the strangest MMO I've ever heard of, but alright

misty glade
#

Why? MMOs can be anything - they don't necessarily need to be first/third person games like WoW/Everquest etc. Old school BBSes used to have "mmos" and it would be hourly "ticks" given the technology constraints

#

Just for the sake of argument - let's say our MMORPG is island/pirates/resources based. You've got a ship, you tell it to sail to a location at 100% throttle (wind? oars? whatever) and let 'er rip. An hour later, you arrive. You tell your ship to start attacking, and it does - firing cannons every.. 60 seconds? You can observe them scramble .. rowboats? cannons of their own? and begin firing back at your boat.

Sorta see where I'm going with that? The above could really be a restful API with some light polling for "has my ship taken any damage in the last 15 seconds" or something.

#

I'm not saying it's ideal, just sorta experimenting/ideating

#

or something

#

maybe there's only a "tick" every 30-60 seconds

plush hare
#

Since the tickrate is so low, you really have a lot of wiggle room here, but I'm confused what your actual question is.

When I hear "REST API" I generally think of actual web requests. Is this going to be an actual web application?

#

for the clients

misty glade
#

No, a Unity app, although.... having a web interface is an interesting idea

#

But our plan was probably PC & consoles via unity apps

plush hare
#

Web server will definitely bottleneck on requests/second long before something like a raw UDP transit

misty glade
#

(maybe tablets although I was thinking mouse+keyboard or controller is going to probably be the minimum common denominator)

#

I'm not touching UDP with a thousand-foot pole. We had some major issues with it in Azure, which is where my expertise is. TCP 4 life throws up awkward programmer gang signs

plush hare
#

Issues like?

misty glade
#

The benefit of the web server would be that scaling it would be infinitely easier

plush hare
misty glade
#

Azure has some wonky firewall configuration that is essentially obscured and prevents UDP from working nicely with containers in their cloud

tawdry crater
#

Is there a server in Spanish?

plush hare
#

that's the universal language

misty glade
#

Our current stack for SpaceGame is a single docker container running alpine linux on 2 cpus and 8GB ram, and it's successfully handled 1000 CCUs and 800k connections over 17 days before we had to restart it for unrelated reasons

#

But the issue for SpaceGame is that we can't easily scale since the "universe" is held in memory on the server and clients are written to the database every 60 seconds. Admin tools (also in Azure) can only read the database, not the memory of the server, so the admin tools generally treat players who are currently online as immutable

#

IE - if you make a change to a player who is online (in the admin tool), the game server will overwrite that document on the next checkpoint write

plush hare
#

I'm not following. you'll need to provide more data

#

Your own custom code should be reading/writing to the database.

#

which should also have access to all of the memory on the machine

misty glade
#

Ok so.. Space Game (if you're US/CA/Israel and Android you can find it on Google Play, or you can try it out on Steam for PC) has a Unity Android Client, a Unity PC client on Steam, a C# headless server, running on a Docker container in Azure, a CosmosDB (also in Azure), and a Razor/Blazor admin app (also in Azure).

The game server is the "biblical truth" - it overwrites the database as it needs to, and maintains most of the state in memory at all times. Players connect (via TCPIP), the server hits the database and says "gimme @plush hare 's player file", and then keeps it in memory. You play the game, talk to the server, the server updates your player data as you play, and when you disconnect/idle off, the server writes your player file to the database and unloads it from memory. The server also writes all players to the database every 60 sec in case of outages/crashes/whatever.

Follow so far..?

plush hare
#

Yes

misty glade
#

The admin tool is a web app - when you go to it and say "lemme edit @plush hare 's player file" it hits the database, and you see a screen with all the player's info. You make some changes, hit save, and it writes it to the database. However, this web app has no knowledge of the game server so .. if @plush hare is playing, the next write from the game server to the database simply overwrites the changes you made in the admin tool.

plush hare
#

Ok. Got it

misty glade
#

This isn't an impossible problem to solve, but it's not really that big a deal for us.

#

The real problem is that if we want to have multiple game servers - there's no easy place for that state to live. The game servers either need to talk to each other (which gets hard when you go to N game servers) or the state needs to live completely in the database and each "transaction" needs to be read and written from the database.

plush hare
#

In the database, you'll need to store the server that each client is connected to. On top of that, you'll need to write a mechanism where your central database server talks to each of these game servers to push any changes

misty glade
#

If the game servers go from "state based C# servers" to "stateless web app" where each and every update or request from a client includes every single data point needed - then we could just go from 1 web server to 100 web servers as needed with the press of a button..... however the client-server communication gets a lot messier

#

Sure - but how to players interact across shards? Our game is fundamentally multiplayer

#

We were thinking of a complex lobby system but.. it got really complicated

plush hare
#

I assume each game server would need to talk to each other then

misty glade
#

Like - any time you wanted to enter battle you'd drop from the "pve server", connect to a lobby server, find a match, then connect with that match to another server

#

Right, and therein lies the rub. Now you need a lobby/gateway server that's coordinating how many shards exist, talking to the servers and pinging them for keepalives, etc..

plush hare
#

If you just have each shard as it's own region, like US west, US east, etc. And have like 10,000 players per shard, you might not need them to communicate with each other

misty glade
#

It gets complicated.. quickly

#

(and what if the gateway server dies)

#

So .. now you see why I'm thinking of a web/restful based solution 🙂

plush hare
#

gateway server, as in the server that lists all shard addresses?

misty glade
#

yeah

plush hare
#

I mean, you could pretty easily make a failover mechanism

#

All it's doing is relaying IP addresses

#

that's not too complicated

#

you could probably do the entire gateway part as a web service

#

the shards you'd want running binary executables though

dusty wigeon
misty glade
#

It gets super complicated 🙂

#

here's what i sketched out a while back

plush hare
#

So one single database?

misty glade
plush hare
#

no load balancing for that?

misty glade
#

something like that for adding a new blade

#

no LB needed - we're using CosmosDB in azure (it's actually super amazing - we've had a grand total of 19 seconds of downtime in the past 4 months)

#

8 of those seconds did cause a server crash but that's because I wasn't caching settings and failing gracefully if players couldn't be written to the database 🙂

#

(now if the database goes offline the reads/writes just fail silently and wait for the next checkpoint to write)

#

even the connection/disconnection workflow gets complicated

#

Most of the issues are around blades coming online/offline and provisioning.. but ultimately I kinda just ignored this problem because we haven't needed to scale ( 😦 ) past 1000 concurrents yet

plush hare
#

You're also going to need something to prevent third parties from acting like shards

misty glade
#

Removing a blade is complicated because you need a way to tell the clients to gracefully switch to a new blade without making the experience "disconnect them and they'll just reconnect to a new healthy blade"

plush hare
#

Why would you need to ever remove a blade though?

misty glade
#

cost

#

Say you .. I dunno, whatever, make front page of Oprah and have 10 million new users. You spin up 500 blades, life is great, and a week later you're back down to your normal load because your game sucks 🙂 You gotta take those blades offline but in the meantime the gateway server has been balancing load on them so there's like 500 blades with 2 users on each

plush hare
#

That ipinfo.io is also unnecessary. The server will know the blade's IP address when they're talking to each other. That's one more redundancy factor not having to rely on their website.

misty glade
#

So.. you have to make a blade have the ability to stop accepting new clients but.. what if someone stays connected 24/7? How long do you give them

#

No, that's for something different -that's to get the IP of the client

#

the blades don't have access to the client's IP since it's tunneled in invisibly due to Azure mysterious black magic

#

(and we want access to IP bans for.. reasons)

plush hare
#

so what's stopping the clients from sending a fake IP address?

misty glade
#

(yes I'm aware it can simply be VPN'd)

plush hare
#

not even VPN, just literally changing the value

misty glade
#

nothing at all, it's just one layer of many we have

#

It's nontrivial to do (it'd require memory hacking of the client in real time) but.. it's not super important, it's mostly for BI metrics

#

etc

plush hare
#

I assume the tunneling is for ddos protection. That really shouldn't happen though with proper ddos protection.

misty glade
#

Well, I don't have any control over the tunneling. I tell azure "gimme a container and give it this dns" and they say "right away sir" and put it automatically behind a bunch of perimeter I don't have any access to (and really, for good reason)

#

Every single request comes into my server as an Azure IP

#

Also - this would be a benefit to a web app.. It would be able to have access to a client IP since my understanding is that web apps have much more robust and well understood ddos protection mechanisms

plush hare
#

If its through cloudflare you wont

#

or any other ddos protection service like that

#

In all honesty you could probably fit 100k users on a single machine with the right code. I think you're worrying too much about the future