#archived-code-advanced
1 messages · Page 65 of 1
The simplest way would be to just group triangles together if they share a vertex. (Using a Dictionary would be efficient)
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);
}
}
}
They stop
Oh. thats good!
Note this is mentioned in the docs:
https://docs.unity3d.com/Manual/Coroutines.html
Under "Stopping coroutines"
because I have an object pooled and want to be sure that some behaviour of previous lifecycle doesn't interfere
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 ?
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
float x = 0;
void Update() {
x += Time.deltaTime * speed;
transform.position = new Vector3(x, f(x), 0);
}```
how do you type it like that in a box
!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.
or its a ss?
That's not what i meant, i mean like the constant speed bezier curve problem
this #archived-code-advanced message is an answer to your original question
Maybe describe this "constant speed bezier curve" problem if you want to know about that problem
If you move it like this it wont go constantly
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
sure it will
Yeah this is what i meant
but the difficulty is how to get proper dx so that it will not overshoot in final step
oh you mean a constant absolute distance per second?
that's not the same as what you originally asked though
I thought of finding an intersection with a radius of a circle but that probably not the best solution
Is there a reason you don't want to just use Unity's spline package?
It has all this solved
Wait really ?
yes
using this, if you just linearly increment t, you will get a motion along the spline at constant speed.
since dy is gotten from f(x+dx)-y so dx=f^(-1) (dy+y)-x
With that package, can you make any function work and not just for the bezier curve thing ?
Our spline technology (which was developped a while ago), is juste lines.
It works well.
Convert any form of function into a series of line.
Then, you use those instead.
Way easier in term of mathematics.
I'm currently looking for a way to convert it, how tho ?
Sample points on your function ?
Ok so how do i sample points ?
You evaluate your function.
Yeah say i already have array of positions
But between them are not in a constant distance
This is expected.
while(x < distance) ...
Yeah then how ?
You just iterate through them
By converting to lines, you mean just pass it to a certain variable in the spline package ?
your problem is extremely hard....
Whoa
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
No I mean,
For [0,10] (whatever value really), sample a point each 1 unit.
Then, you can find the point at the t distance by iterating over them.
The brown is an approximation of the curve.
I still don't understand how todo the iterating part
I'm looking for this
Can i just get those points easily without doing what ティナ explains :)
you just need to find y1 by f(x1), y2 by f(x2),,,,
I still can't understand what "remain" is for
while(distance < Wanted) {
if(distance + segment.Distance < Wanted) distance+=segment.Distance;
else return segment.Evaluate(Wanted - distance);
}
Something like that
yes
You mean, remaining distance to complete the whole displacement from point 1 to point 2 of the divided points ?
Oh
Remaining distance to complete the whole displacement of one small segment ?
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
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?
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.
there's no such thing as "the best" because every game has unique requirements which will be satisfied by different approaches.
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
!collab
We do not accept job or collab posts on discord.
Please use the forums:
• Commercial Job Seeking
• Commercial Job Offering
• Non Commercial Collaboration
I've been working with the FormerlySerializedAs attribute, and I'm wondering if there's a good way to clean them up?
you wanna convert all your old serialized names to new ones? that's gonna be harder than it seems... your best best is manually replacing them in some text editor. won't be too complicated once u get the hang of it, but yeah, it's super manual and there's no official automation that I know of
(clearly you have to enable Force Text as your serialization option in Player settings)
I was under the impression that somehow iterating through all existing prefabs and saving them would do something lol
This tool lets you do this in a few clicks:
https://github.com/rhys-vdw/dirty-boy
thanks, i’ll take a look
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)
I tend to just split the character into a Brain and a Mover
the mover asks the brain what it desires and moves accordingly
sir do you ever stumbled upon for a top down game with gyroscope at smartphone ?
You should just be able to delete them after you reload the editor.
So add attribute (or let rider add them when you rename) -> reload editor -> delete attribute
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
AssetDatabase.ForceReserializeAssets
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?
I am doing gpu instancing
i am talking about finding out at which point i should place the grass patches more efficiently (instead of using raycasts perhaps)
if you can prebake heightmap from the terrain , you can use pixel value to set grass position
same probably goes for normal
im not sure if that would have the desired precision
why not?
wouldn't it be constrained to 256 "heights"?
you can use custom double[,] buffer
or unpack rbga32 into a float
or you can just store the data as is, v3 and normal
okay thank you for the suggestion, I will try it out
i already have those, but is there an easy way to populate the mesh with a given density? let's say I want 3 patches between every vertex
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
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?
tho the whole thing can probably be done offline
if you are planning to use geometry to drive positions, you will be essentially doing exactly what raycast is doing
oooh, i see, hence your suggestion to use the noise map
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
i think i tried that, but i couldn't get it to work. i think you can only cast on the mainthread, no?
oh shit, nice! somehow i missed this.
you've given me much to think about. thanks you very very much for your help!
no problem
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)
thanks, that sounds like just what I need. in my case, I will always have more grass than triangles. now i just need to figure out how to get those weights 🤔
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
https://docs.unity3d.com/Packages/com.unity.textmeshpro@1.0/api/TMPro.TMP_Text.html
have u tried the functions like GetPreferredValues()
not sure what you've tried
not yet I guess
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
so that's the what it calculated for 5 lines (to make it more visible)
one line = 38.25
private float CalculateLineHeight()
{
TMP_Text textComponent = typingField.textComponent;
textComponent.text = "A";
return textComponent.GetPreferredValues().y;
}
i assume that yellow box is the height?
yes
you might have margins between the lines then which adds more space, im not entirely sure
yes, I do have line 30
here is line = 0
and yes, it works perfectly with more lines without line
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
i gonna try
public float lineSpacing
{
get { return m_lineSpacing; }
set { if (m_lineSpacing == value) return; m_havePropertiesChanged = true; m_isCalculateSizeRequired = true; m_lineSpacing = value; SetVerticesDirty(); SetLayoutDirty(); }
}
[SerializeField]
protected float m_lineSpacing = 0;
Ah pretty sure itll just give u back 30
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
Cool glad to hear! Btw to get 3 random numbers that add up to one, just generate 3 random numbers then divide them each by the sum of the numbers. Then those can be the weights.
I just noticed, Rider apparently can't debug unity packages properly?
I set breakpoints but it's totally ignoring them
I am sorry for late reply. I don't think adding just adding works properly.
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);
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?
target position should work fine if you need agents to avoid obstacles. but if you don't want that, you can disable the navmesh agent altogether, make your movements done, then enable them again
I'm making sort of RTS AI movement. So Id like agents to go to a target (wall) and start attacking it since they are approaching from the same direction, they would concentrate in a single point near target. So ideally agents need to have their unique position near the target
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.
For a unity event? Should be fine.
thanks!
it seems my problem stems from doing i < mesh.triangles.Length as a for loop condition. is mesh.triangles.Length an expensive operation?
yes, very
Yep
mesh.triangles/vertices creates a new array each time you access it
Every time you do mesh.triangles it copies the whole triangles array
Just cache it once
And reuse
oh damn, i did not know that
well there goes 3 hours
glad to have finally caught it though. thanks guys!
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
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
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
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
ok ill go back to digging tough that again thanks for pointing me in the right directions 
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
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
I see. well there's an optional for the distance from target to stop from, you can modify that
Yeah, but it doesn't really solves the issue with unique positions for agents around target
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
@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
np!
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
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
ok
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?
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
ah, you implemented Hello World in a visual scripting language
[audience laughs]
not mine
i get the joke
what is it?
a contraption!
node processor on github
for unity?
yes
what is it for?
just open the repo and read
where do i?
node processor on github
that's not c# i suppose ?
i cant
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?
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).
you should use Profiler to see what's causing the frames to take so long. it could be your validation process
no, it's not
as for TMP optimizations, you can go very far by turning off richText and maskable and Parse escapable characters and kerning
it's caused by
typingField.text = niceText;
use the non alloc version SetText instead
what does it mean, sorry?
you can use StringBuilder and SetText instead of that assignment
forget it. seems UI isn't the bottleneck
either way it shouldn't lag your game.. must be something else
as I have written, it lags my game with large amount of text
like 100 words = ~600 characters is ok
and e.g. 500 words = -3000 characters can decrease my game to ~2 fps
yeah it could be TMP's text property setter
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.
it shouldn't lag it, even on mobiles
there should be something, hold on for a while
that's site on TypeScript. The amount of words is set to 5000
you can do String.Create + Span<char> combo and copy the index, this way you'll get 0 alloc..
Browsers' renderers are efficient it never "renders" the text off-screen. As for TMP components, I'm not so sure.
That also assumes you also have nothing else on the same canvas updating, as the whole canvas updates.
hold just a minute. why are u using text setter in the first place?
It's also worth noting how they made this
the validate thing expects a char
yes, they change the letters and I don't wonder if that's possible in Unity too
yes, it does
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';
}
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
yeah, that's how js works
I use it, because I do not change characters in ValidateInput, the text is already on the screen and I just do change character's colors
yeah you're right. it's TMP_Text's fault ;( just tested with a simple validator and it hangs on 7k chars
with all the most performant settings.
does creating my own InputField makes sense?
Maybe try chopping input fields into multiples
the bottleneck is an internal text generator
Could be some batching issues
Yeah, text is expensive, which is Midjourney's issue.
the hangs proly due to ushort limit.. normally it shoulld throw tho
more detailed info
The most elegant solution that I can possibly think of is calculating the height of the paragraphs (for which the text would need to be split by) and offsetting each component using https://learn.microsoft.com/en-us/dotnet/api/system.drawing.font.getheight?view=windowsdesktop-7.0
But I'm not sure System.Drawing is available in Unity.
You mean storing lines as individual TextMeshPros and redact currently changed?
I guess that's great, but now I should think how to implement it 🙄
First you need to figure out if you have access to System.Drawing full stop.
If you don't that is out of the window.
@soft moon use the legacy textfield. it ran 16k chars for me without any fuss
oh man
tmpro getting beaten by legacy
The issue with the legacy is that it is less "clear".
as in visually?
Yeah, pretty sure TMP is sharper
there is still a limit. And 16k for you is < .8k with my methods 🙄
Is this some render issue? If so, what's wrong with chopping it up and disabling what you're not using?
Have you looked at the new UIDocument etc?
what do you mean?
Not sure if that's going to be majorly more performant, but even TMP is aging.
ah, im not too familiar with it's system, but doesn't the fontSize affect it's internal scaling?
UIDocument? I know what that is, but how should it help?
It's the new UI system, I want to suggest it may be more performant but without testing I cannot.
only one way to find out, I guess
I'm not expert on TMP
legacy actually really fuggly with 3d text
I still wanna no limit
it does get easily pixalted at a distance
or not as small
fonSize affects its lineHeight, yes
lineHeight = textComponent.GetPreferredValues().y + textComponent.lineSpacing *
textComponent.fontSize * .01f;
im talking about the legacy text. there's a fontsize field that seems to scale the text without making the quality worse
That's not too bad from the size that I can see it.
But the docs confirm that TMP definitely increase the visual quality (https://docs.unity3d.com/Manual/com.unity.textmeshpro.html).
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?
well the docs also say tmp is more performant...
It's definitely a mystery
I don't think that Font.GetHeight method calculates real line height, just text's
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.
I do have method that calculated line height I guess ?
float GetLineHeight()
{
TMP_Text textComponent = typingField.textComponent;
textComponent.text = "A";
return textComponent.GetPreferredValues().y + textComponent.lineSpacing *
textComponent.fontSize * .01f;
}
That should give you the lineheight plus the current offset of the component. But you'd still need to calculate how many lines there currently are if you were to programmable positiion the next paragraph.
@soft moon so about the legacy textField, make sure you don't change the text field...
just handle everything by returning a char
wait, can you redact the text from inside in legacy textField or..?
What are you actually validating?
onValidateInput method is called when used types a character
that includes Enter, Tab and Space, but does not include Backspace or Delete
you mean like manipulating the text field by character? if so, no, it only gives you a property text and no additional options whatsoever
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)
yes, I am already thinking of it
there is a problem though
lines should be also able to move too
so I guess it should be kind of paragraphs
yeah 👍 seems like a better solution than per line
(to have separate TMP_Textfield per paragraph)
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.
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
Is there a reason not to use a ScriptableObject as a normal class, as in creating a bunch at runtime using it's constructor?
In my opinion, you should not create ScriptableObject at runtime. (I know some people say otherwise)
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
, i just want to use Event.current in the EditorUpdate 
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.
yes, Event.current can be null
even when i interact with the editor it stays null in the OnEditorUpdate, but it works in OnSceneGUI
because that's not where it's supposed to be used? is there a reason you need it to work specifically during EditorApplication.update ?
the Event is a tricky thing to control. when your Editor is not in focus, your Editor will have no control over the received Event. you could use SceneView.duringSceneGui as a hacky workaround, but the proper way is to define a new shortcut
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 
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.
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 😛
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,
}
just add new values at the end
removing old values would still mess it up wouldnt it?
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
yes
i think if u want to stick to enums and allow yourself to reorder/delete values then you'll have to assign values. Other options would pretty much be string based approach or SO
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
Have you considered not using enums at all? Instead make it a ScriptableObject, and create one for each type. This way you/everyone can easily make new types
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)
Don't use enum for that...
You could use ScriptableObject
again - the server isn't aware of SO
That is why you do not separate project.
You might want to use Json then.
You can serialize SO in whatever form the server accepts, your runtime representation doesn't have to be the same as its database representation.
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)
This is what I'm doing. 🙂
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 ?
Yep.
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.
is the "enum" a table in the database?
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
- 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 ?
@misty glade This looks like a really good candidate for code generation
That's not really a pipeline/workflow we support, but it's not one we need either.
Hm, that's an idea too mad
For now ?
Well, I dunno, we're already in production and it's not been a pain point for us at all? 🤷♂️
You can define your table through a more ergonomic form factor like a scriptable object, and then generate the enum off of that
I do agree that the large number of sound effect enums is probably not ideal, but it's manageable
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
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
Yeah but I have my database set to serialize them as strings and since I haven't coded the int representation, I'm not sure if just changing that to integers is gonna blow things up.
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.
I couldnt imagine being an intern for this and seeing 6 pages of enums tbh either...
what kind of db is that?
Well, the SFX enums are quite big, but most enums are pretty tiny
custom?
that should support ints no?
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
ic
once you create a table, you should be able to migrate the strings to ints in one or two steps
☝️ those enums are easier for me (ie, a human) to read
if they are strings in the db then what's the problem with the game/server using strings?
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:
the default enum drawer is pretty limited
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)
you could parse the enum by string instead on the Unity side - might be awful for performance, but theoretically means the order wont matter
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
aye but that's still got the same problem - I couldn't set the value in the inspector with a dropdown... unless I made the field a string field and you'd type in the audio clip name but that's.. kinda awful itself 🙂
Yeah.. I think This Is The Way.
I'm already making it pretty for the admin tool with a utility library that sorts the enums based on .. whatever .. for dropdowns
@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
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
yah, so that can all be encoded in your drawer and nicely separated from your game code
Right but unless I fix the integers in the enum declaration, this breaks when enums are added/removed
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):
the db would own the IDs
(also please don't laugh at my developer art back end.. yes I know it's hideous)
no it's pretty clean actually
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
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
the above screenshot gets rendered in unity as this
and aside from the string ("sir, we're passing.."), it's very very tiny, both from the data side and networking side
I appreciate the amount of internal tooling you've done, that's one of my favorite things to develop haha
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
heh, thanks. want a job? i hate admin tool work 🙂
what are you paying
$0! 😛
haha
(i'm kidding - we're a tiny studio, too small to hire anyone, constantly going broke etc)
I'm actually looking, don't get my hopes up like that 😄
aren't we all
Make you a deal though - download the game, buy a bunch of products, and I'll pay you salary for that much 😉
lol
well, yes, you're going to have to set values in the enum manually and never change them
how's the joke go? mods are asleep, post nudes job offers
thus the append-only db scheme
Yeah.. it's.. OK, I guess.
Mods might be asleep but I'm not, so no off topic please guys
What I'm actually working on is a project template and was hoping to find a better solution to "enum-to-Asset" mapping
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
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
yh, code gen would just make that a bit more ergonomic, but that's essentially what you're doing
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
only way to do it sensibly
and actually looking over my enums file.. yes, I still have sloppy things floating in the pool..
yeah...
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)
I re-assert my suggestion for the append-only local db format
HashMap<StoryBitType> StoryBits;
Assertion passed
oh I got it 🙂 OK, thanks for the convo all
👍
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
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,
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.
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.
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
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.
That item monobehaviour can have a reference to the poco class and pass that to the inventory or whatever system you're using
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*
I don't understand why you need that interface
You can just have a function on the monobehaviour that returns the data class
that is what that is 😅
just in interface form.
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
You are presuming a lot.
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
I am looking for someone who has, and thus probably will see my problem and know the best solution. I can come up with solutions on my own 😅
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?
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!
this looks like a solution in search of a problem to me. Why is a MonoBehaviour involved at all in your example? And if it's a dependency of your not-monobehaviour, why wouldn't you take it as an argument in its constructor?
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.
My Not-MonoBehavior is the dependancy for the MonoBehavior, which is why whenever I make changes to the not-MonoBehavior I am having to change the MonoBehavior. If I break that connection through a variable I am having to add the extra logic to check for the Wrapper.
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.
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
I can understand where you are coming from.
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.
What is more efficient? collider.ClosestPoint vs collider.ClosestPointOnBounds
My closest point will be onbounds because the confronting point is out the collider
This is programing my dude
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?
Dirrectly.
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.
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.
Unity does support partial though. I have this as a character: public abstract partial class Character.
Dang it, just imagine the you sure about that meme. partials on MonoBehavior classes are not supported, normal class yes.
Atleast from how I tested it, there might be a work around I am not familiar with.
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
I am not sure what you were trying to show there.
That you can do partial on class that inherit MonoBehaviour
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).
I have no serialize data in the other, that I can say.
Ah yeah
Anyway, like the other said, you are over abstracting things.
What is the reason why you want to divide Unity and your logic.
Testing, single responsibility, external project use(aka not in unity).
Are you trying to implement Single Responsability with partial class ?
What no, the partial classes was in reference to the blog post, not my problem. I just love partials and thought unity couldn't use them on MonoBehaviors.
I use them in my current project, do not use them.
Just use correct OOP pattern and architecture.
XD oh man. You are using them wrong if you don't like them.
No...
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.
They are great for accessing private non-serializable members of monobehaviours within a custom inspector
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}\"");
}
What key code character was it?
You do you, but I warn you, this is over engineering. You gonna violate an insumerable amount of Liskov principle.
what do you mean? Tab is KeyCode.Tab
Was that what was later printed?
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.
What do you mean ? You can use Reflection for that ? In fact, I am using Reflection exactly for that.
Sorry for late reply.
The issue is that character is being printed, even though I return there
that should finish void method, shouldn't it?
If the return statement was met, the remainder would not have happened.
yes, it is still executed
that's why I ask
Likely two instances of that function where the second didn't qualify for premature returns.
Where keycode and character aren't the same.
no, just one instance 🤔
Print both before the switch.
The return statement will cause the remaining statements inside the function to not have occurred.
This is well defined.
they still do occure
The return never happened then.
I guess for me it’s more intuitive to use a partial class
hwo can this even happen?
You'll get two prints.
Simple as that.
A return statement will ignore the remainder of the function.
how can I even have two instances?
Don't doubt, debug.
yes, let me debug
Instance when referring to the function means that you've called it twice.
yes, I know it
there is written "1 reference"
I wouldn't know. I just know that return would escape the function prematurely.
yeah, that should be so.
1 reference. Called twice or more.
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
yes, I have debugged, it's called 2 times, hold on
It should print twice
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}\"");
}
}
}
Seems that you've got this now 
yes, it's printed 2 times in OnGUI()
frames in OnGUI():
- called and printed Tab
- skipped, cause
case EventType.KeyDown:iffalse - called and printed
$"character: \"{c}\"", causeKeyCode=None, butevt.character=\t
Mystery solved
not solved completely though.
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
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.
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!
I would love to know which for consideration. I am not perfect, and often Unity has engine specific solutions that aren't for other industries. I gauge me breaking guidelines/principles on the best way I know how to make clean code for unity specific/my project specific needs. Ussually try to document why I do so for future developers.
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.
I am not sure I understand what you are saying. Are you asking for which principle you should follow in a Unity project ?
Oh no which parts/how it violates Liskov principle
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.
Ah, alot of that I am defining before hand through IoC, and wrappers around Unity specific(but not game engine specific) logic.
The usage of MonoBehaviour can be one of those implicit contract.
You might, and will, probably depends on how Unity handle MonoBehaviour.
Are we still talking about partial classes?
Liskov principle
Ah.
That was also relating to my previous post about some,,, interesting work arounds, and wrapping none engine specific logic in MonoBehaviors.
I will keep this in mind. I have alot going in my project that hopefully solves(atleast partially) problems that could arise. Also have project design principles that should help eliminate a large portion.
(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.)
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.
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.
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.
Watching a tutorial on coroutines. Isn't this eventually going to cause a stack overflow?
maybe the unity engine internally kill the caller coroutine since there is not any yield after the startcoroutine function call
Are you watching a tutorial on how to crash your editor
no, there is no stack retention for StartCoroutine, it is fire and forget
Thanks!
if you would remove waitforseconds, it actually would.
why not use while loop for that, though?
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.
if you dont yield return in dead loop then the editor freezes...
if you dont yield, it wont compile
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
what is the return type of _wallPartBehaviourFactory.Create()
i remember you cannot new Monobehaviour
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...
I've seen their docs on this, but they seem to be incredibly sparse
if you just want to reference exported functions from a dll you need DllImport, check the docs on that
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));
}
}
Don't use the bottomRight.x and bottomLeft.x of the last character for determining the position of the caret. Try using topRight.x:
float middleX = charInfo.topRight.x;
I cant test it right now but it should work
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?
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
Maybe for large systems
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
I mean i'd give individual large systems their own namespaces
But not really modules inside the system
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
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
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)
Yeah you can define some kind of global usings file... never done it before though
I do, but not in the unity project.. the server project which i believe I'm using c# .. 9?
c# 10 it seems
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
is this a local game, or online server?
online leaderboard for best time
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
hmm
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
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
yeah but why not just fetch all documents and delete them individually
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
what do u mean?
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
oh alright
although im sure mongo has, i just never used it
wouldn't you be able to set everyone elses time to 0 or something
have u used databases by chance before?
yeah, but not inside a client
only I had direct access
it was in discord bots before
updating an entry should be a separate role from inserting entries
https://www.mongodb.com/docs/manual/reference/system-roles-collection/
i believe this is relevant
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
if you can properly link your game to discord login, i could see how it would work
I honestly dont know how you'll verify it at all with discord
hmm
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
sorry, how would that prevent people from hacking my database?
🤔 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
do you mean each person would have their own mongodb account
or
inside the database, that is
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
ok
nope, it doesn't work 🙄
// 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 
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?
should I remove it from the sprite and have it procedurally attached?
basically yes
down the procedural animation rabbit hole I go
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
good idea
You can use discord as a login
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
using a raycast inside a collider that doesn't hit the collider bound hit the collider?
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
You can use 'AvatarMask.AddTransformPath'. Jusst feed root of your transform hierarchy into this function.
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.
any tips on how it functions and what is recursive and how does it build the data inside the class ? there is nothing in the unity docs
thanks for the info btw
You should make one project for the client and server.
I have them as separate projects
Combine them
If recursive is true this function adds whole hierarchy (all transforms) below given root. If false it adds only one specified object
Why?
Literally from the docs: recursive Whether to also add all children of the specified transform.
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.
As a result you will get AvatarMask object that can be used with animators for masking purposes.
- I have already found out that it is best for my case to use separate projects so your answer doesn't make sense.
One project is the client distributed to users and other is dedicated server - I am using networking solution which uses C# sockets so I am free to send/receive any data whenever I want
- It is not. There is no particular reason to use multiple project. The most obvious answer is that you have issue that you would not have with a single project.
- You can, however you gonna need to system that can map gameobject/scene/asset between both project which come already done in most Unity Multiplayer solution.
At the end, you do you. I'm only saying what from what I have experienced work the best.
Synchronization issues (and yes, you will face them) is real pain in ass. Far far better is to make single project, but if you need to separate codebases sometimes, just make some separation tool (script).
You already facing syncronization issues btw (by searching replication tool)
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
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.
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..
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.
It is better to have them originally in the scene.
how come?
Scene loading is optimized/parallelized while instancing is not.
how does the scene load? doesnt it instantiate there too?
It does not. It loads the data from the .scene file which is done differently. (You cannot instantiate asynchronously, but you can load a scene asynchronously)
Perfect
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 ? )
It seem you cannot change AvatarMask at runtime.
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&)```
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
still the same
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
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
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
debug.Log the json string itself
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
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
ChatGPT is often wrong
put them in a wrapper object
You just have to wrap your array dont you ?
it supports arrays just not naked arrays
so boxing works?
[Serializable]
public struct MyWrapper {
public MyType[] arr;
}```
this will serialize
as long as MyType is serializable
yes
If you refer to: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/types/boxing-and-unboxing
I doubt.
yup that works, tyvm 🙂
yea it doesnt box right..
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?
Are you sure it's actually the FOV and not due to a difference in aspect ratio?
https://docs.unity3d.com/ScriptReference/Camera-fieldOfView.html
This is the vertical field of view; horizontal field of view depends on the viewport's aspect ratio.
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
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;
lemme try
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;
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
TMP_CharacterInfo does not contain a definition for bounds
I have to use source TMP_InputField
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
Yeah I dont know why that happens
thank you for your time anyway
@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
xAdvanceproperty inTMP_CharacterInforepresents the horizontal advance width of a character. It indicates the amount of horizontal space the character occupies when rendered within a text element.
👍
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?
For our part, we keep imported asset in their original folder. We made an AssetLibrary, that we use to classify those asset.
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
One guess is that one of them reports actual used memory and the other reports reserved memory
I don't think so, the built-in profiler reports both used and reserved memory of > 200MB
Most likely fragmentation. You might want to use more recent memory Profiler Version. (You can make a snapshot of a old Unity Version and open it in a newer).
I included a break down of memory that we have in our application (On Switch) which was made in 2021 but used 2022 to analyze.
(And yes, we had fragmentation issue that is now solved)
Ok I figured it out. The issue was not field of view or aspect ratio, but our goofy artist who accidentaly exported camera to viewmodel
that makes sense, but I cannot open the snapshot file on any newer unity versions, the warning said my player was too old(built with unity 2018)
does it mean I don't need to worry about the difference memory, if they are indeed fragmentation?
(as for memory optimization, my game cost too much memory)
It depends, 130 MB of fragmentation can be pretty high for android.
but right now I can't see the details of that 130M
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.
is memory fragments included in the used memory value, or is it the value of (reserved memory - used memory)?
It would be considered used
ok thank you sir
Borther this made me crack up hahahaha
Relatable
hah, I've done this before
"why is the game running so terribly? i only have five characters in the scene..."
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
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
Not as far as I could find. But if you're iterating over a coroutine yourself in a method which returns an IEnumerator and is executed with StartCoroutine(), then you can pass the values back out to Unity's coroutine iteration if and when you find appropriate
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. 🙂
@misty glade this series comes recommended and goes down the line on everything you need for mmorpg
here's an overview video https://www.youtube.com/watch?v=61Z2jsKnc6I
There is a book titled "Development & Deployment of Multiplayer Online Games", which is currently on Kickstarter. The book is written by 'No Bugs' Hare, and infomercial is read by live rabbit. Now it all starts to make sense, I think...
and a second volume https://www.amazon.com/Development-Deployment-Multiplayer-Online-Games/dp/3903213152
When you CreateInstance on a ScriptableObject
Are those instances located somewhere?
I've only done theoretical studies (and small scope project) on deployment of high scalable and high availability (99.999%) application. What I leant was revolving around Docker/Container, but also technologies like Kubernetes and the studies of Microservices. You might want to look into them.
If you're not running a simulation on the server, players can and will cheat. Creating a real "MMORPG" involves much more work than most people realize.
"but typically only need to send messages to the server every 20-30". Is problematic if you're actually going for a real mmorpg.
Yes, in memory
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
Well those are two different questions, but no . . .
Nothing that you create in code is an asset until you actually make an asset
Through something like Asset database.CreateAsset
Which doesn't even exist in builds anyway
I figured. Just had to ask. Thanks.
Which is the best Online Course to learn C# for unity from beginner to Advance ???
there's no such thing as the best, but there are some links in pins #💻┃code-beginner and #archived-code-general
Just so we're clear on experience level - I've already built and published one game using always-on TCPIP with a server that's .. reasonably resilient to cheating. 🙂 Players still try but we have pretty good defenses.
I think it depends - this won't be a "twitch" or "fast response" game. Think more like piloting a boat - your actions will take a few minutes to unfold and while reacting to changing conditions quickly will be important, it's not going to be something like a FPS
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.
That's the strangest MMO I've ever heard of, but alright
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
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
No, a Unity app, although.... having a web interface is an interesting idea
But our plan was probably PC & consoles via unity apps
Web server will definitely bottleneck on requests/second long before something like a raw UDP transit
(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
Issues like?
The benefit of the web server would be that scaling it would be infinitely easier
You would also need to spin up more instances than a VPS running a binary executable
Azure has some wonky firewall configuration that is essentially obscured and prevents UDP from working nicely with containers in their cloud
Is there a server in Spanish?
This server is mainly English, sorry
that's the universal language
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
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
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..?
Yes
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.
Ok. Got it
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.
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
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
I assume each game server would need to talk to each other then
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..
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
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 🙂
gateway server, as in the server that lists all shard addresses?
yeah
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
By using Kebernetes you can assure availability and redundancy for any server issue.
So one single database?
no load balancing for that?
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
You're also going to need something to prevent third parties from acting like shards
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"
Why would you need to ever remove a blade though?
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
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.
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)
so what's stopping the clients from sending a fake IP address?
(yes I'm aware it can simply be VPN'd)
not even VPN, just literally changing the value
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
I assume the tunneling is for ddos protection. That really shouldn't happen though with proper ddos protection.
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