#archived-code-general
1 messages ยท Page 413 of 1
also the solution im gonna use is that github repo and this code
no idea if its what i wanted, but the values look good enough i guess
if you want to visualize this stuff, ask chatgpt to do it for you.
it will use code analysis
pay for plus
i mean the $20/mo
why not use stuff that's specialized specifically for that kind of stuff
It doesn't matter what the mean is or whatever, from that curve they draw, for example f(7) is about 5x as f(350), so what they want is for a 7 kg fish to be 5x as likely to appear than a 350 kg fish. They want to be able to randomize according to this curve, and they want to be able to adjust this curve.
I've already explained the general algorithm to achieve the "randomize according to any curve" part. If doing the integral is a bit too hard math wise, then well you just have to pick curves that you can do, or use a library that handles all the integrating for you.
instead of, yknow, a hallucinogenic LLM
๐ฅบ
its just that iam to stupid to understand what you wrote, i copied it into notepad to study it later but its definetly waaaay above my knowledge
it's just that it's wrong
don't worry about it
How is it wrong?
you wanna explain why?
I can do an example calculation right now to demonstrate how it works.
i mean what Burrito wrote is exactly what i want (function wise)
any example would be great, im down to test it out, the solution i have now is not ideal since it still has many high numbers
a way to think about this is, that if you want the "Average" fish to be about 20kg, choose a scale of 1/5, because that is 20% of the way between 20kg and your "max" of 100kg
so you want weights between 1 and 100. you will discard and reroll above 100kg.
so something like randomexponential(scale=1/5) * 100 + 1. if it's greater than 100, reroll.
here is the plot, which is basically what you want
does that make sense @unkempt swallow ?
If you did computer algs or probability you'd run into it
They want adjustable curve, not just one specific curve.
idk what you described with words, but the picture is correct, thats what i want
i know
yes, so i can use it for something else, lets say i want the reverse, i want many high numbers and low numbers should be rare
the important thing is that when you want something like "really rare fish weights", but for gameplay purposes you want to discard fish above 100kg, i mean, go for it
im so confused rn 
i already wrote what you need to do
how do i achieve this with the randomexpo function that wants min and lambda, i thought i understood but im getting weird results
randomexponential(scale=1/5) * 100 + 1. if it's greater than 100, reroll.
Exactly, and the method I've outlined will allow you to do any curve, curves that falls off, rise up, dips in the middle, whatever you want.
But anyways, if you want an example math to go through I can write it out, otherwise I'm just going to exit the conversation because it seems like your attention is split.
the min is 0
scale is lambda
please write the example
i mean i don't think they're really going to go for integrating their own functions given the lack of confidence with math that theyve stated
i know how to translate what you want into statistiquese. but. if you just asked chatgpt to author this for you from scratch, it probably would succeed
seriously listen to me and ignore that stuff
it just isn't correct
anything you want to do something random. you know, there's what you want to achieve with gameplay. i already told you the best way to do it is to create a deck, and replace the cards after you draw.
but if you don't want to do that, the thing i am describing is basically the same process
from what i read i think you both are saying the same thing but you are saying their solution is wrong
this means nothing to me
RandomExponential rnndn = new RandomExponential(0,0.025f);
i thought this would be correct but it isnt
okay, well you wrote 0.025f, which is 1/40
i think you should maybe take a breather
or ask chatgpt to do it for you. it will give you a correct answer. buy plus
so if i want 100 to be the max i use 0.01?
no.
why are you here to sell chatgpt lmao ๐
๐ฅบ
It's so absurd
if you want to have a very specific behavior, generate a deck of 100 cards with the weights written on them. then when the user draws, do not remove the card from the deck, just shuffle it again.
@unkempt swallow you wanna have a try with an animation curve?
yes please
you can't turn an animation curve into a histogram...
it doesn't work the way you think it does
you would just be doing the process of making the deck
and drawing from it
you wanna explain?
you drew a histogram. yo ujust don't know that you drew a histogram
look at the title of the chart i got out of chatgpt. i asked for a histogram. an animation curve evaluated at time t, where teh aniomation curve is a histogram, is telling you the frequency of that value
see. that's because you're all confused. he was indeed drawing a histogram. that is a PDF...
you can't just draw a PDF and sample from it.
i dont think recommending gpt is wise here
one sec
you would have to do another step. which is exactly the same thing as what chatgpt did, which is generating a bajillion samples. and then you're back at square one
๐ฅบ
listen anything is possible!
you are overthinking this
can you just copy and paste this with backticks?
i can't edit a screenshot for you
just gonna test it first, since it wasn't my idea lol
don't waste your time...
@unkempt swallow everything you need is directly in front of you
can you copy and paste your code
into backticks @unkempt swallow
just do that for me
RandomExponential rnndn = new RandomExponential(1,0.01f);
float thenumber = rnndn.Get();
testlist.Add(thenumber.ConvertTo<int>());
this is my current code
!code
๐ Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Does anyone know how to make for exemple i pick up a key and then lets say when i turn around a jumpscare plays whats it called?
well, you're triggering something by picking up a key, but the jumpscare to happen you'd probably check if it's currently in the viewing frustrum after spawning it
@north hatch
i really think you should pay for chatgpt plus
you are in a good place and very aspiring
it will help you with a lot of instruction
okay
i am beyond poor bro
cause im making a story game and i need it
this is a simple enough problem for o1 mini
why is there a while loop
that's what it means to redraw
why do i even have to redraw / discard
this stuff will get easier
thats like wasted computer power no
because that's what it would be in real life
hmm. well the last thing i'll say is the general approach to these problems is
try to do it how you would od it if you were implementing a board game
it doesn't matter at this scale, computers are really fast
in cardware. then you can translate your cardware board game rules into code. it will be a lot easier
that's why i said, make a deck of a 100 fish. then shuffle it. then look at the top card. that's your fish. then shuffle it and look at it again for the next fish
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Renderer.OnBecameVisible.html
There's a good call for it, but you'll want to make sure you only spawn it after picking up the key
you dont know if i plan to catch 9 decillion fish per second tho
using this i get only 100, 100 times
no computer would be able to render that, this part is not going to be the bottle neck lol
i can't ad hoc program for you
in the discord window
i've told you a bajillion times how to do this
i've even shown you a chart that gives you what you want
using the code you posted i get 100 times the result 100
@chilly surge please ๐
i didn't want to program into the discord chat window
you still are responsible for writing your own code
i think you are best served by asking chatgpt
wtf
didnt we get here because of chatgpt
no, but the user has received a lot of very specific guidance
yeah ok the animation curve works fine as far as i can tell
and ultimately wants a snippet of code that "just" does what he asked for
animation curve is bff
Here's an example math:
Let's say you want to randomize a fish's weight in the range 100 kg to 200 kg, with a customizable curve. Let's say you mess around and end up with a curve like y = 0.2 * x + 100 and you feel like that's the one, now here's how you would do the randomization part:
- Integrate
y = 0.2 * x + 100, you get a result of0.1 * x^2 + 100 * x + C. - Plug in
x = 100(your lower bound), you get11000 + C. - Plug in
x = 200(your upper bound), you get24000 + C. - That's it, in your code you can use
Random.Range(11000, 24000)to get a random number.
Let's say the randomizer gives you back20000, now you need to calculate what kg of fish it corresponds to: - You solve the equation:
0.1 * x^2 + 100 * x = 20000, which gives youx = 170.8, so player fished up a170.8kg fish.
This math uses y = 0.2 * x + 100, but the same calculation works for any curve you want, so you can adjust the curve to however you like and plug in the same math to randomize fish weight according to it.
๐ฅบ
the animation curve by itself doesn't solve th eproblem. you still end up sampling it...
there are
a million ways to do this
i'm not saying one is right or one is wrong.
and it doesn't involve any math
listen to yourself
im not saying it's better
imagine having to go on desmos and visualizing your curve
it's more achievable for kinami
no one has time for that
yeah... we'll see about that
because you can just draw something like this and not do any math
yeah...
if you are just evaluating that curve with random t 0 to 1
it won't be correct
is that what you are doing?
what is it exactly lol
You did say that others are wrong and to ignore them though ๐
it might be a cdf, idk ๐
but you don't need to know any math to use it
isn't that what kinami is asking for though?
it's not hard to turn the exponential dist pdf / histogram into a curve that works the way where you draw it and sample it, but they're not the same!
you need to know math to do that transformation!
do you need to do that transformation though?
well...
exponential curve might not work in the general case anyways lol
why should i?
it's okay. we've spent enough cycles on it
because the histogram is how you measure the behavior
sure
it's how you know if you did it right
@chilly surge you can draw a curve that is a histogram. but the way to use it is to create a "deck" of "1,000" cards, each with a value written on it from animationcurve(random.random). then shuffle the deck, then draw a card, then discard thd eck.
does that make sense?
it's not enough to just call animationcurve(random.random)
Sorry but I don't think you even read what I've written, it has nothing to do with animation curve.
if you want to draw a curve that is the inverse of a pdf, you can, but that is hard
It's a video game, I don't think anyone notices if the random distribution uses a perfect math formula or if it's sampled from an animation curve
okay, i think what's confusing about this is, what does the value of the curve represent? what is x, and what is f(x)?
before you take any of the other steps
so what if i draw a line between 100kg and 200kg. what does it mean?
succinctly
before these steps with integrations or whatever
which, btw, is just doing the histogram, and sampling from it. this is valid! i sort of know what the curve means. there are lots of valid approaches. but at least say succinctly, what does x and f(x) mean
^ It's been clarified long ago.
i used the chatbot to create the distribution he wanted
this makes it sound like f(x) is the probability of drawing x?
that's a pdf then, yes?
you actually want the inverse of the pdf, not the integral
does exactly what i intended it to do
๐คฆ
well we can only reason about stuff that makes sense with real math no?
I'm done with this conversation, OP got what they asked for.
there's a reason that's what people use to communicate things
this isn't a math server lol
here we get stuff done, unlike mathematicians
lol
i appreciate that this was a stylized comment. but c'mon guys. if you want to elevate above the chatbot, you should adhere to like, real educational stuff
as much as i love being admonished for telling a "juster" kind of user who "just" wants an answer for using a chatbot. well... it's fun to talk about what's really going on
if you want to draw a pdf using an animation curve, that is, the user needs to draw a curve in the eidtor that looks what he drew earlier, you would need to compute the inverse of it
that's just the approach. you wouldn't take the integral
If you believe my math is wrong, you are welcomed to sample according to the math I've given above and see for yourself that the resulting histogram does match the curve given.
i just punch into google "how to sample from pdf" and the answer is "inverse of pdf"
which isn't generalizable for something like gaussian, which you can see for yourself in all the implementations
i can't believe people are coming out as anti-math!
seriously everyone will write much better games if you learn this stuff
i've been talking for ages about modeling it with decks. that's really good for designing games too!
This is beyond Unity related now, move on.
Good thing is I don't need to Google to know my math is right and is verifiable by running a simulation yourself. But yes I shall stop here.
If you want to continue debating this, you can make a thread.
anyways, @unkempt swallow, if you're still interested in using an animation curve;
with a serialized AnimationCurve, you can edit the curve directly. it would basically be a mapping between the Random.value and the output value.
for example, #archived-code-general message with this example, the min value is 5, there's a high chance to get values around 30 (the flat area), there's a 75% chance to get an output under 50 (consider the value at t=0.75)
histogram for that demo curve: #archived-code-general message
when drawing the curve, make sure to edit the start and end points to be at exactly 0 and 1, and set the min/max that way as well (right click the points > edit point)
right click the points to set the tangents to weighted to freely control the curve, and you can add more points as needed
to sample it, you would do curve.Evaluate(Random.value)
Movement inside car
i understand everything besides the last thing you said, i think it contradicts what you said before?
when drawing the curve, make sure to edit the start and end points to be at exactly 0 and 1, and set the min/max that way as well (right click the points > edit point)
right click the points to set the tangents to weighted to freely control the curve, and you can add more points as needed
to sample it, you would do curve.Evaluate(Random.value)
can you rephrase this
i think the animation curve does nothing at all, because you still use Random.Value, so lets say i get 0.8 which on the curve would be at .8? what is the point of the curve, i dont understand
0 to 1
ohh time is on the left
i see yeah
animation curves are normally for, well, animations, where the x axis is time, and the y axis is what to do
I use animation curves for this kind of thing pretty often
ye
this is great and i think i will use this often, exactly what i wanted
what my friend helped me with is this now
public float decay = 1.5f;
public float GetRandomRarity()
{
float randomValue = Random.Range(0f,1f);
float rarity = -Mathf.Log(1 - randomValue) / decay;
return rarity * 10;
}
which gets me basically values up to infitiy lmao with the option to adjust
ill stick with the anim curve tho, i like the numbers more 
in 100 rolls, only 5 were above 0.5, perfect
ty ty
If I am going to use steamworks inventory system thing later for my cosmetic stuff, is it smart to use like scripteble objects and save them in some way until I get into steam works? or should I make it in anther way for a more smooth transition?
there are a lot of good options. i suggest finding an inventory and cosmetics management asset store asset that supports steamworks
ok so this code was ORIGINALLY made to apply to transform.rotation.z and not rigidbody2.rotation so i switched it to rigidbody to comply with physics instead of bypassing it by changing from Quaternion.Euler() to rigidbody2.MoveRotation(). It kinda works but once angle reaches 180 it snaps to -180 and vice versa. If this isn't the right way to do this then I'm not surprised but unfortunately I don't know the right way (why does rotation have to be so complicated)
private void AimMouse()
{
Vector3 mousePos = Input.mousePosition;
Vector3 objectPos = Camera.main.WorldToScreenPoint(transform.position);
mousePos.x = mousePos.x - objectPos.x;
mousePos.y = mousePos.y - objectPos.y;
float angle = Mathf.Atan2(mousePos.y, mousePos.x) * Mathf.Rad2Deg;
Debug.Log(angle.ToString());
rigidbody.MoveRotation(Mathf.Lerp(rb.rotation, angle, 0.05f));
}
hello guys
sooooo I've been trying to find the solution for this problem, but haven't been able to
I'm creating this one pixel art 640x360 game and I used to be making it in Gamemaker 2 since it was the engine I used to use but the project's code became complex really quickly and now I've needed to transition into Unity if I didn't want the game's specs to be ridiculously high. In GM2, sprites can be rendered through a single function which does the job, however it seems like the only way to render sprites in Unity is by using the sprite renderer component but this doesn't allow an asset to render more than 1 sprite at a time which would be very useful to create many things.
TL DR: I would like to know if there's a function which renders sprites, thus allowing more than a single sprite to be drawn with a single asset instead of having to create an asset with the sprite rendenr component for each sprite
by the way, despite being a complex project its camera always only displays a 640x360 slice of the game so it shouldn't be problematic to use a single game object for each sprite since I'll use a rendering deactivations for offscreen regardless, it just isn't ideal
you use many game objects with sprite renderers to render many sprites, just how it works in unity. Very normal!
Unity has many things to optimise drawing many sprites, make use of spritesheets where you can.
Look into particle systems too
if you mean can you render multiple sprites at the same time with one SpriteRenderer then refer to what the guy above me said, but if you just mean rendering different sprites with one SpriteRenderer then that's definitely possible, one method is to the SpriteRenderer's sprite directly at runtime by referencing another sprite
public class Example : MonoBehaviour
{
public Sprite spriteA; // The first sprite
public Sprite spriteB; // The second sprite
private bool spriteToggle; // Whether to use the first or second sprite
private SpriteRenderer sprRend; // The GameObject's SpriteRenderer Component
void Start()
{
sprRend = gameObject.GetComponent<SpriteRenderer>(); // Get the reference to the GameObject's SpriteRenderer Component
}
if (spriteToggle) // If spriteToggle is true
{
sprRend.sprite = spriteB; // Set the SpriteRenderer's sprite to spriteB
} else // Otherwise
{
sprRend.sprite = spriteA; // Set the SpriteRenderer's sprite to spriteA
}
/*
Toggles the sprites. You would need to call this elsewhere at runtime by getting a reference to this GameObject's Script's Component, and then doing Example.ToggleSprite(). Alternatively you can Invoke the function with a callback from a button or similar
*/
public void ToggleSprite()
{
spriteToggle = !spriteToggle;
}
}
funnily enough im also porting a GM2 game to unity so if u have any other questions i (might) be able to help you
I did find out a function which does exactly that
Graphics.DrawTexture()
Can somebody help me with this code i cant find the solution. I want it to do a dash with an animation of dash. The dash was pretty ez but after the dash it keeps itself in that animation and is in the last frame until i change the state so if i move it works again but else it stays in dashstate
drawing meshes this way is a good idea if you have many thousands to draw but for normal games its not needed
ohh I see
GM2 is great for getting into game dev but it does have a great amount of limitations and badly optimized ends, unfortunately
normal, as in like, a default amount of effects and sprites?
unless you need to draw tens of thousands of textures and sprites at the same time u dont need to bother with it i think is what he meant
its going to be different per game. If in built solutions dont work and profiling confirms the problem is too many game objects/ poor batching then its worth looking at code only mesh drawing.
what are you trying to do? is this a top down adventure game with a rigidbody based character that you move using point and click?
use the built in sprite renderer and its toolset
absolutely do not use Graphics.DrawTexture at this stage
for a 2d game
that you have barely started writing
even for thousands of sprites
but what are the cons of DrawTexture, exactly?
your computer is drawing thousands of sprites right now right in front of you (the text glyphs). trust me. you should use the sprite renderer
you will be reinventing SpriteRenderer.
unless you are doing vampire survivors level of sprites then you probably dont need it
vampire survivors uses sprite renderers!
oh i know. i got to speak to one of the devs last halloween at their party ๐
what's the problem in that?
I've reinvented all mechanics until now lmao
my game literally requires its own physics engine and collision logic
I have a squishy garlic ๐ง
okay. what if i told you graphics.drawtexture is slow
it's top down but it's not point and click, it's a 2D space game.
it's not exactly physics based it just uses the linearVelocity attribute of Rigidbody2D so I can have acceleration and deceleration without any of the complicated transform manipulation business.
previously AimMouse() used to work with transform because it was bypassing physics but now I'm changing it so it doesn't do that and it has resulted in unexpected behaviour (as many abrupt conversions do)
it is always going to be slower than spriterenderer
vampire survivors has a port of the old engines physics engine (from the old js engine) as they needed it to be exactly the same
but due to perf issues they stagger some things on different frames.
if you want it to feel very physicsy you can use a joint (like a spring joint) and connect the rigidbody in a bunch of clever ways to a transform that follows your mouse to it
ah, right
this will give you physics and a nice framework for experimenting with controls if that's your goal
hmm, is vampire survivors really done using sprite renderer?
yes
110%
why wouldn't it? why assume that something right in front of you would be slow
nah literally all i need it to do is rotate towards the mouse using the rigidbody, I don't plan on having it feel very drifty or anything since it's supposed to be paying homage to a game I used to play ages ago and that game didn't have very drifty space physics either
unity can reason about all of your sprite renderers at once
I've gotten used to writing everything from zero
as I've said, the game already has its own physics and collisions mechanics, not using components at all due to optimization and control matters
unity can't reason about a bunch of DrawTexture calls
hmm. okay listen. you aren't optimizing things. i mean it's unknowable if you are
it might feel that way
and i get it. it matters, something that feels true is true
you may want to change that, components are basically unity's lifeblood .-. (you can work around them but i really REALLY recommend you dont)
but you don't actually know
come at this with an open mind
keep chugging along
you can go ahead and use graphics.drawtexture. nothing bad will happen
if that makes you want to work on your game.
though, as I've also said, the game will not be cluttered with sprites in each frame like Vampire Survivors
so I'll sprite renderers instead
if you are looking for validation, go for it
(unless I notice optimization problems, then I'll have to get deeper into meshes and etc.)
choose whatever will make you excited to work on your game
unfortunately mouse driven rotations with rigidbodies are very tricky
i would use the appropriate joint that can transfer the rotation with very high "Stiffness"
that's how i do it in all my games
so that it's non kinematic but still feels very snappy
I could show the game to prove the point, but to sum it up it has massive levels with entities that can interact with any other entity and deactivating entities outside the screen would be non-ideal (I think, I'm considering splitting levels into several rooms to make that more manageable)
computing the right amount of angular velocity such that the rigidbody very stiffly rotates towards the mouse and abruptly stops rotating when it is facing the mouse is exactly as hard as implementing a framework for joints
@kind nymph does that make sense?
thinking about this and skimming through the spring joint documentation actually made this seem a lot more appealing
okay cool
of course I would need to tweak the settings so it doesnt bounce too much
but thank you for the insight ๐
if you are excited about stuff like this, use ECS
I looked it up but it costs
plus I don't think my game is that complex either
does anyone know if i can single out and debug a script ran by an object that other objects are sharing that script? For an example if have a bunch of enemies running their own enemy script. How can i debug one particular enemy and its script ?
if using a debugger you can set conditions to check on breakpoints. I often do something like check for a local var value or you can even do gameObject.name == "blah"
if logs, you can add a context object as an arg to Debug.Log: Debug.Log("foo", this);
i see ! i didnt think of using conditional break points to do that, though is there a faster way to single out the game object for debug ? The bug im trying to pin down happens semi often and i would prefer not to having to manually change the gameObject name everytime
well unless you can create a condition that identifies this object then its not going be easy
Sometimes its wise to add a check in code manually somewhere to detect a bug so you can log it and even pause the debugger.
yeah the bug im having doesnt really cause run time error but just some logic error that is causing animation issues for my objects. I guess ill just stick to conditional break points. I worked with Unreal for a little bit and it was much simpler whenver I wanted to take a look at a specific object to debug. Im too spoiled from that lol.
thanks for the help!
or, if you haven't figured out how to use conditional breakpoints yet, you can just throw in
if (someCondition) {
Debug.Log("Put the breakpoint here.");
}
no thenks, iM tOo LaZy
dunno how you did it in unreal but its not a unity specific issue.
it is sometimes better to just add an if for the breakpoint condition as conditional breakpoints can reduce framerate
you have any tips super hard to find
This isn't a very technical question more so design choice. Say I have a lot of instances of some entities(e.g. animals) roaming around all using the same material&shader that displays vertex colors. I want when they are damaged to display a different color, like red. Should I quickly switch out the materials? Create new material properties? Have a buffer for all instances and also detail which entity instance a vertex is in its vertex information passed to the shader so I can just change the buffer's information?
That depends a bit on which render pipeline you're using
Material property blocks would be my go-to in the built-in RP
that lets you override specific properties on each renderer
In the scriptable render pipelines (URP and HDRP), the SRP Batcher only works if you aren't using material property blocks
you're intended to just create a material instance for each renderer
(by accessing renderer.material)
If you're rendering a huge number of non-skinned meshes, you could do instanced rendering. In that case, you'd want to use material property blocks again
Thanks for the input, Iโm using URP for skinned meshes(theyโre animated), I want the render pipeline to avoid creating a draw call for each instance, in terms of performance I think itโd be much more preferred if I just inject the instance index through as a vertex property to lookup in a buffer. But that is a pain to setup obviously.
You can't avoid the draw calls, AFAIK -- you're drawing many different meshes (after skinning)
but the SRP Batcher can give you better performance e
I see, I guess quickly switching the material isnโt that bad, if I just have two shared materials for each state. Just wondering whether there was a more correct way
It should be roughly the same to have:
- one material for "normal" and one material for "hurt"
- one material for every single renderer
I'd guess the former is better, but the SRP Batcher can handle both
Thatโs fair I suppose the difference is pretty negligible, this whole conversation is pretty nitpicky
dunno if this should be in general or advanced coding but here's what i wanna do.
i want to make an editor script that accesses the selected imported textures from the project and allow me to assign secondary textures to them via script.
but i dont know if it's possible to access and set the secondary texture in the project.
is it possible to get and modify this information in script instead of manually clicking one at a time?
i was planning to make a script to set them all in bulk based on my naming convention
Wdym by "secondary textures"? I'm not sure there's such a concept in unity or gamedev in general..? In relation to textures.
It's a sprite thing
It lets you associate multiple textures with a sprite
I also completely forgot about that and had to google it :p
yeah, sometimes stuff like specular maps, emissions and etc
A sprite is just a reference to a texture + where to sample from it
yeah, but basically what i want to do is get code to access the ability to add/change the secondary texture so i dont gotta manually add it in for hundreds of textures
I'd ask about this in #โ๏ธโeditor-extensions . I suspect you just need to look at an example of a Sprite with secondary textures to figure out the correct serialized properties to look at
I see a secondaryTextures property in here
(I copy-pasted a sprite sub-asset so that I could look at its actual serialized data directly
i see, so it probably would b e about getting the file and guid and type to add it
It seems like you can pass them in when creating the sprite:
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Sprite.GetSecondaryTextures.html
Refer to the example on the page.
Ah, there you go
Now, if you're trying to modify the secondary textures for sprites produced by an importer, that's a different story
I'm not really sure what you'd need to do there
maybe an asset postprocessor..?
hmm, well i guess i have to look into any possible access to the texture importer scripts..
getting an importer for an asset is often the best way to modify it
Would you do that in a postprocessor?
I'm still pretty uncertain about this stuff myself
Last time i did this i just had a menu item to go over many sprite sheets to change some settings on their importer
how do you get at the importer?
I think you use this and cast it to the correct type
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/AssetImporter.GetAtPath.html
make sure to set stuff as dirty and save the changes after
ooh, okay
that makes sense
changing importer settings in a postprocessor wouldn't make sense
an example from something i did a while ago:
TextureImporter texImporter = (TextureImporter)AssetImporter.GetAtPath(assetPath);
if (texImporter != null)
{
EditorUtility.SetDirty(AssetDatabase.LoadAssetAtPath<Texture2D>(assetPath));
TextureImporterSettings texsettings = new TextureImporterSettings();
texImporter.ReadTextureSettings(texsettings);
//9 is the custom alignment mode
if (texsettings.spriteAlignment != 9)
{
EditorUtility.SetDirty(texImporter);
texsettings.spriteAlignment = 9;
texsettings.spritePivot = newPivot;
texsettings.ApplyTextureType(TextureImporterType.Sprite);
texImporter.SetTextureSettings(texsettings);
texImporter.SaveAndReimport();
}
}
i had issues with shit not saving hence the weird dirty ๐
this looks interesting, thanks. i'll mess with this another time to see if i can get the result im looking for
hello guys. I've made up a level manager/quest system and all the quests are stored in a list so when i finish the x quest i just go to the x+1. all the quests are scriptable objects (structure in the image). In my json savedata i just save the index value corresponding to the element in the list so i can retrieve easly at which quest i am when i start the game. So all good the "main quest" is done. But i also want to have the possibility to have more quests going on (so sidequests). What you suggest to save in the json for other quests going on (can be multiple ofc). A list of the indexes of a list filled with the side quests? Seems an easy answer but i cant find a solution i like!
if i save all the possible sidequests in a list i could easly access them and save the index of all the sidequests going on. but i dont know why it sounds wacky and there is a better way
saving indices is very delicate because if you update your game, they might drift, and it could break people's saves (which maybe is fine! up to you)
you could auto-generate some kind of UUID for each quest and use those to reference each quest uniquely. In practice, I recommend giving them unique string names because it will make your life easier keeping track of everything.
do you mean unique string names that i write. so i load all the quests from the resource folder, use a dictionary of strings and retrieve the quest?
yep
sounds good indeed
so i can also attach the quest to where i need in the scene instead of numbers
I would recommend loading them from some kind of 'active quests' object so that you can have quests included which aren't 'live' yet, but it doesn't matter that much
if you want to do this, you might want to make your quests individual ScriptableObjects
yes they already are indeed
nice, there ya go
and how would you deal with the rewards then. For now for the main quest i have a big class with switches that gives rewards according to my needs
one advantage to readable string IDs is that for debugging it's nice to be able to do stuff like /grant quest tutorial_combat_1
if each quest is an SO, you can define the rewards on there
my eyes are too pure to look upon anything ugly
behold
rewards can be of anything
i dont really understand how a scriptable object can do that
using a prefab with a script that does only that probably?
yeah, and that might be valid as well
what I would do is define my rewards as data
they can't really be anything
yeah sure
they can be unlocking a skill, or setting an element, or adding an element amount
and you can define those in a list of rewards with an enum or something in your SO
so i could put in there some flags to represent which reward is it and with some editor scripting making it pretty
yep, and then somewhere you'd map that enum to the actual code to 'grant' that reward
when i do these things i always think "why do i need some value when it may be not used". thats why sometime i get stuck..
for example in my scriptable object i have the float Distance and the list of objectives to complete
which represents two way to complete the quest
sometimes you can define things abstractly enough, where it's like 'a type and a value' and then you don't have redundancy
the answer is 'because your code is simpler if it can assume that values always exist'
ahaha yeah good one
so i should eat what i have and dont worry for now. there will be time to polish
you can have different 'configuration' objects that you switch between in the editor based on the type of quest selected in the dropdown
the thing is, 'configuring your game' does not need to be the same as 'running your game'
yeah man, to making it simplier to program youre making it harder to finish
so if it makes sene to have some ugly extra data in there at design time, but then at runtime you build up some objects from that data which are simpler to work with and only have the pieces you need, that's good
alright thanks again, ill delete this class full of switch lmao
yeah generally if it works then go for it, but you already have an object for each quest so it would feel much better to me if the rewards were defined on there too
yeah i always thought of it but never did it
cause in my mind "what if i need that, or that! or this!!"
of course, sometimes the rewards are highly contextual and it doesn't make sense to say 'this quest always gives this reward', in which case maybe having some systems which handle reward distribution at a higher level like you have make sense (but it would still be good to use tags and things to organize them instead of a per-quest lookup)
the eternal struggle
oh one last question
I've landed on 'write only the code you need, only when you need it, and keep it as easy to delete as possible' ๐
easiness of deletion is a one of the few good code quality metrics
as you can see in the ugly rewards method im using some managers to update the rewards. those are actually services (im using a service locator). In this case its best to attach prefab for the rewards right? cause i dont know if its a good thing to use it in scriptable objects (if its possible too)
sorry i mean, im referencing the managers directly. but i might need to use the service locator
it's not something I'd worry about on a solo project
C# is really easy to refactor
service locator is probably technically better but I don't expect it will matter, and if it does it's pretty easy to go through and update those
folks have differing opinions for sure
Hi! I'd love it if someone could give some of my code a review. I'm interested to know if there is a more efficient / better way to approach this problem. Please give all feedback as it will help me become better :D
Here is the link: https://paste.mod.gg/txnqnxukazyj/0
A tool for sharing your source code with the world!
For a bit of context, this is a almost done piece of code that I've written in the past couple of days. It is for a skill tree in unity (by almost done I mean its just missing some of the skill effects, I still need to code those but the framework is done). I've commented the whole thing so hopefully that should help
Here is also a screenshot of what it looks like in unity (visual WIP, I don't have art for it yet)
Each smaller white square is a skill node, the larger one is purely for visuals and the cancel button explains itself
Here is also a screenshot of what the inspector for the script looks like:
Skill TXT is just where I assign what visual elements explaining the skill tree I want set active
Thanks!
(Also I'm sorry if this was too large)
You could use switch cases for checking your enums instead of a bunch of if else statements
I am wondering, why you always use FindGameObjectsWithTag instead of handling them in script
Oh yes, I agree with File_Missing, def. look into switch cases and also try not to hardcode values in your script for example increasing health. That should come from some kind of SO or list or database in best case.
Imagine you want to extend your skill level and experiencepoint checks to way bigger numbers. you do not really want to mess around with x amount of if statements to get the correct amount of health, stimlevel or whatever all those values are ๐
Why do you have region for every single method
Thanks! I think I might actually look into databases now that you've suggested it :D. As for not using switch statements..... I didn't want an if statement inside every switch case. I did try to use them originally but you cant have another condition in the same line as the switch statement (at least that is my understanding of it) and I need to check multiple conditions to allow the skill to become active.
Its looks more organised that way XD.
Hi all, is there a way to properly search for a tag where there is only a single instance of the gameobject with such a tag per scene? But only when the scene is loaded and the old one is unloaded?
private void HandleSceneChange(string sceneName, bool showLoadingScreen)
{
_InterfaceEventChannelSO.RaiseEventLoadingScreen(showLoadingScreen ? true : false);
new Task(SceneChangeLoadAsync(sceneName, OnSceneLoaded));
_InterfaceEventChannelSO.RaiseEventLoadingScreen(false);
}
private void OnSceneLoaded()
{
CameraManager.Instance.UpdateFollow(GameObject.FindGameObjectWithTag("Player").transform);
}
private IEnumerator SceneChangeLoadAsync(string sceneName, System.Action callback)
{
AsyncOperation asyncLoadScene = SceneManager.LoadSceneAsync(sceneName);
while (!asyncLoadScene.isDone)
{
yield return null;
callback();
}
}
my current problem is that it finds the tag of the player from the previous scene in editor mode and returns null in a dev build
You should make this data oriented so you can expand it (such as adding another level) without changing code
Also should try avoid using singletons
How come?
Yeh the problem lies within your hardcoded stuff. You need to think of it in a more generic way. So a skill tree is a list of skills in a hierarchical order for example. So you could have skills referencing child skills or whatever fits your needs. And then loop check your enums to get the right values back for all your stuff you have in there. So bascially your if loop hardcoded would become your hierarchy in inspector for testing and later in whatever dataformat you want (json preferably or just a simple SO yada yada)
Because your code is hardcoded and impossible to add another character with own skill tree and experience etc
Ah. Ok. I will try to avoid using them in the future
new Task with IEnumerator? what
Is that even compile or is that Task your own something
Solved: built-in function OnLevelWasLoaded(int) works
yes my own
If there is only one, use the singleton pattern for that one
Why
lol, singleton hater cathei? ๐
They aren't inherently bad IMO, this is just not a great usecase for it
i initially just got into unity at the time and coming from aspnet i didnt really do much coroutine work so I had no idea what i was doing tbh
but the code is sacred rn and on the backburner for cleanup
but thats also not your question, right.
If you're from asp.net you probably already familiar with dependency injection concept
There are libraries that supports it and you don't have to do "singleton pattern" shit
This is preference.
objectivity left the room, I guess ๐
If you call bad code a "preference"
Oh boy, we got it. you hate singletons.
And you love it because you don't know how to properly avoid it? ๐ค
ill probably look into it, i too also have a slight distate for singletons. but seeing as this is part of my portfolio for uni applications i would prefer to learn something that is easier to understand for my future teammates. i think dependency injection is lovely too but not for people largely without coding background at all (as the way it is for the program im aiming to enter)
I do not love it. But it makes sense, if you have one player in the whole game (which I assume from his code of find by tag "Player"), to just have a static reference everyone can access at all times. But you do you and as you only raging and not really giving info about WHY you think its bad, I could not care less.
I use it where it fits, I have no reasons to avoid it
Have fun when your director want to support split screen.
Splitscreen for a singleplayer game?
Why not? You think "We want to add co-op game mode!" never happen?
Or "we want to let player control different character mid-game!"
ohhhh, thats the reason? So starting a project with ALL possibilities to come is a profound way of going bankrupt. If there would be multiple players needed, a singleton doe snot make sense. But you are just rying to prove a point with arguments, that are flying by randomly. Again, I understand this as a singleplayer game, so singleton fits to this target. If his plan is to make it coop, thats another story and another way of doing things.
Relying on singleton is simply making your code inflexible for no good reason
And judging the whole pattern if someone misuses it, is like hating hammers because someone hit their thumb with it
Its giving you access to one source of truth of a specific class, good reason for me. Imagine having a datamanager load stuff or return textures you can load dynamically. You gonna hate singleton there too, because what if we want multiple datamanagers? (which does not make sense)
The only issue I have with singletons is that everybody resorts to implement it with a static variable. I feel like having a general provider that provides shared instances works a lot better here
But I get, that you are not a fan of it and thats fine with me. Still I would love to read a suggestion / solution how you do it, so I can learn something new probably. Honestly always interested in other ways of doing stuff, if its not filled with raging subjectivity
That said, rejecting singletons because you might need more instances is a very obscure reason. You can give edge cases for everything, but that doesn't mean an implementation is bad
Just make sure you're not tied to it. Singletons are fairly reasy to scale on
Sounds like "I'll not make my code modular and I will rewrite everything when design changes!"
Sounds like you continue with raging on me, so I step out of this conversation. No outcome for me here
If you have a main singleton provider that provides instances rather than a static variable everywhere then the code is very modular
You can always make your singleton an interface and then swap out the implementation if needed
The reference needs to be stored somewhere tho
Which, by the way, is how .NET generally does it using its IServiceProvider pattern
Singleton registered to a IoC container is fine. It is not "singleton pattern"
Which imply access from static instance variable
I haven't seen good arguments against using a static variable
And no i'm not talking about static in general, im talking about the singleton usecase
You also can't always assume that everyone develops for a massive team
There's nothing wrong with it, it works fine for the majority of people
There's always a better approach, and like everything else it has its issues
Does anyone have any good resources where I can learn about databases in relation to unity?
You sure, you want to go with databases right away? assuming you try to put your skilltree there?
For easier development to learn relations to data and your actual runtime object, I would go with some simple SO or inspector list to start off, testing around. Learning to serialise data from and to json. Database might be a bit too over the top to start off
Are you asking for example of issue from using static instance variables?
Yes, specifically for singleton access
Not to deviate from the path, but also think of using a file-based approach instead of a database. Pretty sure most games resort to that instead
Ok that's fair advice. Just from what I was able to look up now, databases are more for multiplayer games, however, my game is a singleplayer
In the end, your skilltree could be only ONE field in the database returning an array or what not. But you just want that array right now to fiddle around with your skills ๐
void UpdateColors(Player targetPlayer = null)
{
if (targetPlayer != null)
playerList.transform.Find(targetPlayer.UserId).Find("Color").GetComponent<Image>().color = colors[(int) targetPlayer.CustomProperties["Color"]];
HashSet<int> usedColors = new HashSet<int>();
foreach (Player player in PhotonNetwork.PlayerList)
{
if (player.CustomProperties.ContainsKey("Color"))
{
usedColors.Add((int) player.CustomProperties["Color"]);
}
}
foreach (GameObject color in colorButtons)
{
if (usedColors.Contains(colorButtons.ToList().IndexOf(color)))
{
if (color.GetComponent<Button>().interactable) color.GetComponent<Button>().interactable = false;
if (!color.transform.Find("X").gameObject.activeSelf) color.transform.Find("X").gameObject.SetActive(true);
}
else
{
if (!color.GetComponent<Button>().interactable) color.GetComponent<Button>().interactable = true;
if (color.transform.Find("X").gameObject.activeSelf) color.transform.Find("X").gameObject.SetActive(false);
}
}
}
i'm making a multiplayer game with photon pun where players select colors in the room, but when i'm updating the color buttons with this function, the buttons which are already claimed flicker (they become interactable and the X text on top of it gets disabled for a split second). how can i fix this?
That the "this exists only one" assumption is hardcoded to your code. Already mentioned that if your player is referenced Player.Instance of such you cannot add another player without massive refactoring.
I mean its not too hard to add or subtract skills rn. To make a new skill, I just add an entry to one of the code paths (enum 2) , then add the else if statement under that branch in OnClickCheck(), and then I add what I want that skill point to do. Besides, before I actually made the skill tree I spent a while concepting out how I want it to work, so it should not be a huge amount of fiddling
Until you are at a complexity and things start to break. Then you gonna hate yourself for not structuring it in a more dynamic way
Yes yes, that's just singletons in general. I wouldn't use a singleton for a player in most cases.
I would probably use a singleton for an audio manager though, for example. This isn't related to the static variable access anyway however.
I'll look into it definitely, but for what I need right now I think my solution is ok. Thanks so much for all the advice though :D
If you use dependency container with contexts you're just able to switch between singleton and non-singleton, not only implementation
With the same logic, you would always use float[] instead of float in your code, "in case you need more later"
(not related to your most recent message)
One more question, based on that code that I wrote, how advanced would you say I am? I'm just try to gage where I am :D
If you ask that question you are a beginner.
yeh, might be the best answer. you are advancing everytime you learn something. So how much "advanced" are you, I do not know, but you are missing some core conecpts that you still have to learn. Not really a question, someone can easily answer from one script ๐
What core concepts?
It's also relevant to what your audio manager requires. It might need reference to the output device, or the player so it can calculate distance from sound source and whatnot.
And if we want to expand the whole singleton assumption does not work at all on something like server or generic libraries, so why not be consistent.
Most people understand way less than they think they do and the more you understand the more you realize that you actually know nothing.
I am struggling with my UI I am coding with ui toolkit , my dialogue text pushes into the dialogue options below: https://pastebin.com/80wEC6gc
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
I guess it all boils down to the complexity and needs of your project
Introducing people to new concepts or alternatives is totally okay, it just irks me when one says you "can't/shouldn't ever" use something, when it works for a lot of people's usecases
Using DI doesn't really add much complexity anyways, if not simplify code spaghetti.
Did you manage to continue ? I'm trying to do more or less the same thing
Also DI (containers) introduced in a project where most devs donโt โget itโ is basically a death sentence for productivity. People will abuse it to recreate the bad patterns that it was supposed to fix.
I use player singletons when Im lazy and making a one-off game
I would encourage any team to figure out patterns that solve their specific workflow issues (from a team perspective) and be very sensitive to the actual dev experience and subtle nudges any such architecture decision produces
usually when cooperating with others in a project many things that make sense solo suddenly become a crippling liability. And there is a desire to find ways to restore that solo dev productivity.
void UpdateColors(Player targetPlayer = null)
{
if (targetPlayer != null)
playerList.transform.Find(targetPlayer.UserId).Find("Color").GetComponent<Image>().color = colors[(int) targetPlayer.CustomProperties["Color"]];
HashSet<int> usedColors = new HashSet<int>();
foreach (Player player in PhotonNetwork.PlayerList)
{
if (player.CustomProperties.ContainsKey("Color"))
{
usedColors.Add((int) player.CustomProperties["Color"]);
}
}
foreach (GameObject color in colorButtons)
{
if (usedColors.Contains(colorButtons.ToList().IndexOf(color)))
{
if (color.GetComponent<Button>().interactable) color.GetComponent<Button>().interactable = false;
if (!color.transform.Find("X").gameObject.activeSelf) color.transform.Find("X").gameObject.SetActive(true);
}
else
{
if (!color.GetComponent<Button>().interactable) color.GetComponent<Button>().interactable = true;
if (color.transform.Find("X").gameObject.activeSelf) color.transform.Find("X").gameObject.SetActive(false);
}
}
}
i'm making a multiplayer game with photon pun where players select colors in the room, but when i'm updating the color buttons with this function, the buttons which are already claimed flicker (they become interactable and the X text on top of it gets disabled for a split second). how can i fix this? i've tried rewriting the function in many different ways but it didn't help.
totally agree 100%, but couldnt add the emote ๐
Singletons arent truely static though and have a lot more uses than just being some static accessor to some data. You can always just not flag it as Don't Destroy so when you load the next scene you can grab a whole new (specific) instance instantly from that same accessor
Oops, blocked ๐
And I feel like that's expect because there's no way to get any actual entry point to data when loading a new scene
haha, wonder what I did to that person, cant remember. well, sorry then ๐
That'd be bit of Unity specific issue
You know one massive issue with singletons is that you can't depend on eachother. A provider would solve that too singe you grab your instances from a generally available location instead of having the risk that the singleton wasn't initialized yet
The only issue is ensuring the provider exists, which is a lot easier than fiddling with the order of everything else
TBH Unity should have had a Main method
The concept of a singleton in unity is so fundamentally misunderstood and abused that it has lost most of its meaning. Most use and understand it as basically a static public variable and donโt get the uniqueness property at all.
Then you end up with ProviderProviders
You can just make sure there's a script that is invoked before anything else, which initiates the provider
Which, note, by itself can use the whole singleton pattern. You have to do that anyway in order to access it
You should call it a service locator cause thatโs what it is.
Yep, exactly
I guess this could be used for an entry point
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/RuntimeInitializeOnLoadMethodAttribute.html
Yes, this is a very good solution
It's also that if you intend on changing the lifetime of objects, you can specify it in here before the provider has to start providing at all
That is what most of DI libs use
.NET APIs also have a period where you can register dependencies before it runs
It boggles the mind that a service locator is such a trivially easy improvement over the singleton, yet nobody uses it and continues with the singleton nonsense for silly โconvenienceโ reasons.
Yeah, that's generally why I mention them
I'd argue it's even easier
Also itโs a very small step from a service locator to DI container if you later decide to go that way
So you would have like a main ServiceLocatorClass that holds reference to all other providers and on the scripts accessing those providers, you now access the servicelocator.provider?
Services.Get<IMyService>();
Hey all, could anyone help me figure out why my videoplayer does not have any audio? The video part plays just fine. I have it set up as follows
private VideoPlayer vp;
private AudioSource audioSource;
...
vp.audioOutputMode = VideoAudioOutputMode.AudioSource;
audioSource.volume = 1.0f;
vp.controlledAudioTrackCount = 1;
vp.EnableAudioTrack(0, true);
vp.SetTargetAudioSource(0, audioSource);
vp.Prepare();
yield return new WaitUntil(() => vp.isPrepared);
Debug.Log("Done preparing cutscene video");
vp.Play();
audioSource.Play();
Yeah GameManager being the only singleton you need is probably the best way around it, but there's one issue with that and you end up with some very large variable accessors ;p
No, game manager public singleton is also an anti pattern
there is no need for the systems to know about the manager as a whole
God class
systems should only depend on the bits of information that they actually need and that info should be injected
Seems hard
Itโs always hard until you realize itโs not
You expect that GameManager to know the state of the whole game at all times
you do the thing constantly, out of necessity, in all your normal code, you just never think about its directionality
opposed to keeping some independency between the objects. I mean in a perfect project it would make sense but that seems like a lot of extra work
Why are you making these assumptions
The game manager is just another system that also only knows the tiny bits that it must control
No system knows everything
the service locator or di container also just knows how to create or where to locate a service/resource but nothing of what it actually is
Generally: you can break down your game into states that defines part of your game and services that uses those states
Oh and if you feel this makes it annoying because you canโt just call methods on anything at any time: thatโs the whole point.
just use 1 big script for your entire game /s (some guy on twtr did this :|)
I'd probably have to look into that idea more. Feels like you'd abandon a lot of how Unity even works such as ignoring a lot of the instantiation calls.
You can use these principles of separation even in monolithic scripts, itโs not something that relies on language features to be possible ๐
that is true if you have many classes at play but just 1 "monobehaviour"
i wouldnt do this but i guess its certainly possible
Not at all, that is a misunderstanding, if you abandon unity, youโve gone in the wrong direction
the only situation where you need the service locator is for a component on a dynamically spawned object to find its managing system (usually part of a scene or other persistent context), register with it and receive all the remaining init/dependencies from there
https://hastebin.skyra.pw/qorelonede.java
So, I'm having trouble with the Kinematic Character Controller's swim functions.
Using crouch and jump buttons don't descend and ascend like the walkthrough does. What am I doing wrong here?
The Yandere way
thankfully miside came along to save us (it uses unity 2021)
Start debugging all those velocity variables
I've actually been refactoring my code as I changed the approach a little bit, would be happy to provide some assistance on what I do have
Okay, can someone please tell me the current working way of updating the mesh collider mesh at runtime? The project is an URP project in 2021.3.45
Tried a bunch of fixes from forums and none of them work 100% of the time.
Unfortunately sidewalks are an unsolved problem
Literally guide for it https://docs.unity3d.com/Manual/prepare-mesh-for-mesh-collider.html
It's doable with some vector maths
How is the road mesh generated in the first place? Sidewalks generation wouldn't be too different from that
What do you mean with updating it? Swapping it out or modifying the mesh?
And what issues did you run into?
I made procedurally generated terrain divided into 2x2 unit chunks. Each chunk creates a mesh that is used both for rendering and collision. When I use terrain destruction functionality, the rendering of the mesh updates but the collision sometimes doesn't.
How do you modify the meshes, on gpu or cpu
(Also 2x2 is a weird chunk size ๐ค )
Or is that just the size in the world, but resolution is higher
it's 100% CPU side at the moment
2x2 is the unit size, it's 12x12 vertices
it's a top down game so it doesn't really need more detail
Are you sure you aren't passing invalid mesh data into the meshcollider
That's self intersecting polygon with the edges of your mesh, you could try different things to detect it. You could find if n and n+2 (or n, and n+ ... , non consecutives) edges intersects, or calculate winding number of diferents points on the left or right of each edge
That should give some warnings at least
We can't help much without seeing the code or other details tbh
to give a bit more context, this is called each time a mesh is recalculated:
private void UpdateMesh()
{
if (_mesh == null)
_mesh = new Mesh();
_mesh.Clear();
_mesh.vertices = _vertices;
_mesh.triangles = _triangles;
_mesh.RecalculateNormals();
}
which should make sure the mesh is completely replaced with a new one I imagine? the _mesh variable is then applied to both mesh filter and collider
majorly doubt it, it's always a flat plane with modified vertex heights, nothing spatially fancy
You might need to notify the physics engine about the mesh/collider changing somehow
@covert dust Try if something like this helps
meshCollider.sharedMesh = null;
meshCollider.sharedMesh = mesh;```
I did as the first solution I found online
๐
as I said, none of them resulted in anything
some of them even worsened the problem
Said it here, but that's not important, thanks for the suggestion anyways
yeah sorry, that was literally the first google result ๐
When it happens, does the mesh collider seem to use the previous mesh data?
Or does it not work at all
And did you try messing with the cooking options (such as disabling all)
okay, to make matters funnier, I reverted it to the pre-fix state and tried to reproduce the problem and it's not happening at all
๐
it uses the previous data
was planning on getting on that
Wdym pre-fix state, what's different
// here it calculates new vertex heights
UpdateMesh();
_meshFilter.mesh = _mesh;
_meshCollider.sharedMesh = _mesh;
UpdateMesh() being this
this was the original state before I tried any fixes
okay, it finally broke
took me like 5 minutes of nuking the map as I generate new chunks
hi
And bye
soooo, a 2d sprite is just a plain rectangular mesh with a texture, right?
Yeah, it's a quad
You can see its triangles if you turn on wireframe mode in scene view
can I render a single 640x360 rectangular mesh for an entire screen, and draw textures inside it to optimize the game?
Wouldn't just scaling resolution easier
draw calls bad! so i will instead of an mega shader that somehow layers 100+ sprites together! /s
it's actually worse to do that?
Of course. gpus are able to handle many tris and batching helps combine many meshes to be drawn in 1 draw call
(the message was sarcasm btw)
ah I see
yeah I see lol
I'm still learning about meshes and textures
in fact, I'm actually starting to
guys can someone make a short tutorial about how to make a skilltree in unity
I think this depends on your game's speccific code a lot
how do you mean depends?
void UpdateColors(Player targetPlayer = null)
{
if (targetPlayer != null)
playerList.transform.Find(targetPlayer.UserId).Find("Color").GetComponent<Image>().color = colors[(int) targetPlayer.CustomProperties["Color"]];
HashSet<int> usedColors = new HashSet<int>();
foreach (Player player in PhotonNetwork.PlayerList)
{
if (player.CustomProperties.ContainsKey("Color"))
{
usedColors.Add((int) player.CustomProperties["Color"]);
}
}
foreach (GameObject color in colorButtons)
{
if (usedColors.Contains(colorButtons.ToList().IndexOf(color)))
{
if (color.GetComponent<Button>().interactable) color.GetComponent<Button>().interactable = false;
if (!color.transform.Find("X").gameObject.activeSelf) color.transform.Find("X").gameObject.SetActive(true);
}
else
{
if (!color.GetComponent<Button>().interactable) color.GetComponent<Button>().interactable = true;
if (color.transform.Find("X").gameObject.activeSelf) color.transform.Find("X").gameObject.SetActive(false);
}
}
}
i'm making a multiplayer game with photon pun where players select colors in the room, but when i'm updating the color buttons with this function, the buttons which are already claimed flicker (they become interactable and the X text on top of it gets disabled for a split second). how can i fix this? i've tried rewriting the function in many different ways but it didn't help.
if (usedColors.Contains(colorButtons.ToList().IndexOf(color))) This is very inefficient
.Contains() part?
No, you are creating list, then looping over that list to find index
Which you could get it for "free" if you just use for loop
You might want to add video or something to show what you mean by flicker/disabled for a split second
alright imma record it
Hello! Need some help reducing the size of my game.
The total user assets size is shown as : 31.7mb
but the total build size gets to 141 mb,
I have set Managed Stripping Level to High.
That has taken down 20 mbs as my build size was originally near 159mbs.
Done all the optimizations to assets as Images/Textures/Models, etc
Don't know what to do more to get the size down to around 50-60 mbs
And is UpdateColors only place you are updating those?
turns out that's all i needed lol
i feel dumb
i forgot about another function which runs when the player selects a color and i completely forgot about this part
tysm
? anyone
hi hi how heavy is VR with regards to performance? My game renders many materials and gameobjects as well as lights. It probably won't be able to deal with VR
Not something suitable for this channel. This is a coding channel.
I have no idea what would be the best so you should probably just ask this in #๐ปโunity-talk. People there probably point you to the correct one if needed
for (int i = 0; i < colorButtons.Length; i++)
{
if (usedColors.Contains(i))
{
colorButtons[i].GetComponent<Button>().interactable = false;
colorButtons[i].transform.Find("X").gameObject.SetActive(true);
}
else
{
colorButtons[i].GetComponent<Button>().interactable = true;
colorButtons[i].transform.Find("X").gameObject.SetActive(false);
}
}
is this okay?
Yeah, that looks much better.
If you can reduce GetComponent/Find calls then it's even better but it may involve some refactoring.
You should never use Find methods. Considering you're on component level already you should be able to just use GetComponent here
Also a styling note, you could simplify your code here because it only differs in the boolean. If you would like an example here I can provide it
I feel like you can make it even simpler considering usedColors appears to be a subset of colorButtons. Is it?
no, usedColors is a hashset created in the same function
HashSet<int> usedColors = new HashSet<int>();
foreach (Player player in PhotonNetwork.PlayerList)
{
if (player.CustomProperties.ContainsKey("Color"))
usedColors.Add((int) player.CustomProperties["Color"]);
}
Ah, then let's forget about that part ๐
i was thinking about creating these 2 variables to replace GetComponent and Find calls
[SerializeField] private Button[] colorButtonComponents;
[SerializeField] private GameObject[] colorClaimedOverlays;
i already had these 2 for the buttons and the colors before
[SerializeField] private GameObject[] colorButtons;
[SerializeField] private Color[] colors;
so would it be efficient to create a struct to combine these 4 variables?
There's no need for the GameObject array
Just use the button one
But yeah use a struct
yeah i think i'll do that since i don't use colorButtons itself right now
Better way is having a component that holds related information for your object, for example ColorSelectionButton, then other components can reference that component.
Then you can properly capsule what you do into methods like colorButtons[i].SetInteractable(!usedColors.Contains(i))
the engine itself with all assemblies still needs some space, even if you build an empty project you will have ~100mb
nvm realised now you had this answered elsewhere
I know that Debug.Log can be quite bad for performance. Would this be a good solution to remove Debug.Log from production builds?
namespace MyGame {
public class Debug {
public static void Log(string msg) {
// we're in a production build
if (!Application.isEditor && !UnityEngine.Debug.isDebugBuild) {
return;
}
UnityEngine.Debug.Log(msg);
}
}
}
I don't see why it would be bad for performance. Where did you find that info?
Generally the logging sink of Unity is always through this, or the ILogger which basically does the same (except keeping gameobject context)
experience, and e.g: https://discussions.unity.com/t/does-debug-log-effect-performance/525017/2
I do this for editor/debug build only logs:
#if DEBUG
Debug.Log("foo");
#endif
Very interesting
logging a lot at runtime isnt good as it does write to various places and generate call stacks
You can always make a wrapper method and use the Conditional attribute which targets DEBUG
This way the method will be stripped out in builds, or applications without the DEBUG conditional
I suppose ideally you'd make a general logger that uses Debug.Log as its sink in DEBUG, but a different one in production. I can imagine you'd still want to log warning/error/critical level log message
Serilog works super well for this, and is the most popular approach
Debug.log will do stack tracing and write to a file, it is surely bad
[Conditional("DEBUG")]
static void DebugDebugLog(string message)
{
Debug.Log(message);
}
You get the idea
I'd use Serilog though. You can filter based on classes if done right so you can just turn off everything you don't need
thanks!
note tho, [Conditional("DEBUG")] will touch the IL land, while #if UNITY_EDITOR or #if DEBUG wont
Still better than wrapping every single call in a conditional ๐
Omits the performance issue at least
will touch the IL land
Why is that bad?
It means that it's not fully stripped. Rather it checks on invoke if the method can be called
Which is a really negligible difference
.NET also has code contracts. I believe this is the real way of doing this. Never used it though.
Really goes over my head when I read these things
Oh, nevermind. This is for .NET Framework
No idea where I got this idea from then
code contracts are like the more powerful version of [NotNull] , [MaybeNullWhen] etc, they're just for verification
Been seeing them everywhere. I guess I was looking at really old code then
they're useful, you can specify that method doesn't return on some condition for example, which in IDEs like Rider will give you better warnings, like if you have an AssertNotNull method you can tell RIder it'll throw if you pass a null object in, therefore all usages of the object after that don't need a null check
i assume VS can do that too but i'm a Rider for life person lol
Note
Code contracts aren't supported in .NET 5+ (including .NET Core versions). Consider using Nullable reference types instead.
I wish I could ๐
well they work in Unity ๐
you can alway polyfill them if it's not supported, it's not that hard
oh yeah in Unity it's provided by Jetbrains.Annotations
My unity is taking too long to load empty scenes in async mode, spending 5 sec or more
So? whats the question, whast the code ๐
I've noticed that a lot of the time spent on a scene load is actually from unloading another scene
including a big GC pause
Physics.Raycast(ray, out RaycastHit _hit, HUDSelectMaxDistance, HUDSelectLayermask))``` I want the Ray, the RaycastHit, and the LayerMask. If I remove the distance parameter, it treats the layermask as maxDistance. Do I just pass in Mathf.Infinity as the maxDistance, or is there a nicer way to do this?
why not just lookup the signature ?
or just use the named parameters thing to arrainge your own order, you just need the correct amount of params
yeah, infinity is the default value
Wait what? I can do layerMask = 5, ray = this.ray, etc.?
What is a signature?
layermask : mylayer maxDistance : myDist
etc.
':'?
yes, this isn't python lol
mhm that lets you place parameters in any order you want, but yeah you still need the same amount
if it were = it'd be ambiguous with an assignment
foo(bar: 1)
I guess. I just thought I was setting the variables of the method (idk)
well you kinda are, but not through assignment
So I still need a maxDistance value?
yeah for that specific signature yes
each signature has its own order and number of params
I'm confused. I'd assume that as long as they had a default value, they'd be optional paramters
if it has = in the signature, it means you dont have to write anything cause it has default value
I see
So since maxDistance has a default value, I don't have to write anything for that paramter?
if you use a signature with a default value, you don't need to no
default iirc is mathf.inifinity
your IDE ideally should help you
Raycast has over 16 signatures
So in my example: cs Physics.Raycast(ray, out RaycastHit _hit, HUDSelectMaxDistance, HUDSelectLayermask) I don't want the HUDSelectMaxDistance
How do I doi the out thing?
they don't overlap; if they did that'd be an error on the declaration
Think you just need to pass in mathf.infinity like you originally said
Yeah you can just pass that again
Okay, but how would it work with this way of doing it?
wdym how?
named parameters just let you pass stuff out of order
yeah you stil need the same amount , just can be placed in diff order
not sure how that relates to passing Mathf.Infinity to one of them
But what about the default valuesa then? They don't apply in that case?
the signature you chosen probably didn't have default value
I'd still have to pass a maxDistance?
It just says in the docs: cs public static bool Raycast(Vector3 origin, Vector3 direction, float maxDistance = Mathf.Infinity, int layerMask = DefaultRaycastLayers, QueryTriggerInteraction queryTriggerInteraction = QueryTriggerInteraction.UseGlobal);
I see
eg
public static bool Raycast(Vector3 origin, Vector3 direction, out RaycastHit hitInfo, float maxDistance, int layerMask, QueryTriggerInteraction queryTriggerInteraction); ```
Is there a reason that it doesn't have a default value like the other?
no idea, thats something some unity dev thought of
just pass Mathf.Infinity same thing
Alrighty. Thank you for answering my many questions ๐
The signature from the source code ```cs
static public bool Raycast(Vector3 origin, Vector3 direction, [DefaultValue("Mathf.Infinity")] float maxDistance, [DefaultValue("DefaultRaycastLayers")] int layerMask, [DefaultValue("QueryTriggerInteraction.UseGlobal")] QueryTriggerInteraction queryTriggerInteraction)
I wonder how defaultvalue attribute works
Some c++ shenanigans i guess
oh shit didnt see that, thanks
Also... aaaah
static public
Looks so wrong to me, i always do it the other way around
Might just be for documentation generation.
lol oh wow its reversed
that threw me off for a sec
ohh its actually working.. huh TIL
Shows up here
That would make sense
The other overloads are excluded from the documentation
I dunno why they did it this way instead of just having one definition with default values
Perhaps it's more convenient for other code generation
so Axel, Raycast has 16 different methods, all named Raycast. c# knows which method to use based on what type of inputs you give it, what order its in, and how many inputs. For example foo(int num) and foo(string num) are declared in the same class. if you use foo(37) youll get int, and if you use foo("37") youll get the string method. This is called overloading a method, when you create different methods with same name, but different inputs.
Debug.Log is slow in the editor, because it causes the Console window to redraw
in standalone builds, it is hard for it to matter
If I have a large number of meshes (and colliders) under a single gameobject (which will have some physics applied to). From a performance standpoint does it make sense to merge those meshes together?
The meshes will share some common geometry so I should be able to remove a few faces here and there
Is it a car?
Itโs empirical. Thereโs no hard and fast rule. https://assetstore.unity.com/packages/tools/modeling/mesh-combine-studio-2-101956 read the docs for this to understand more
so I've just used the multiple sprite mode in a sprite to accommodate a sprite sheet
what is the C# class which represents a multiple sprite mode sprite sheet?
the Sprite class only fits a single sprite in it, not a whole sheet
The importer settings determine how the importer interprets your texture
when you use the "Multiple" mode, it creates more than one Sprite asset
There is no "multiple-sprite" type
ahhh I see, thank you
what is your goal
@polar marten It could be a car, or plane, or boat. Boat I think has the more interesting complications, if using the mesh collider for calculating bouyancy
you should use a tool to combine the meshes, and read the documentation
it will explain all the limitations / what is required to get a performance boost from mesh combining
physics it's much simpler. the more colliders, and the more faces on those colliders, the more expensive collisions are to calculate.
Does anyone know how to make a very smooth camera in unity
Cinemachine + Tutorial
like this
Exactly, learn how to do that by following tutorials.
actually, when the multiple sprite mode is used it does not split the sprite into multiple different assets
the spritesheet is still a whole image, however I suppose it has the properties to tell a sprite renderer or animation clip what the position of each slice is so it can render the sprite
It does make multiple assets. If you expand the texture asset you will see those subassets.
The "spritesheet" is just a texture
each Sprite is an asset that tells you:
- which texture to use
- where to look on that texture
Ah, no, that does not happen.
for context, I'm using DrawTexture instead of SpriteRenderer for optimization matters
use cinemachine
Very suspicious statement you got there
since you decided to do this, you might as well not import sprites at all
Did you actually profile your game
i don't think you have to worry about it.
Or you just assume there will be perf issue
first person
cinemachine is a very capable camera system, even for first person games
the previous discussion = the user wants to write his own sprite engine for fun. so it goes
actually, not really yet
however I already know each entity will render more than a single sprite and thus I don't want to create an additional game object for each sprite needlessly
i wouldn't worry about it
Care about batching instead of that
batching?
it's not really possible to engage since this is all being written from scratch
Reinventing the wheel
I see
yeah, exactly
don't stress about it
Your draw call is batched if you use correct atlas setup and material
i think you'll figure it all out
however, I'd still like to know what batching is
but like, batched how?
Look into frame debugger
what would that do?
does batching allow a sprite renderer to render more than 1 sprite at each frame?
No? It means multiple sprite renderers' draw call can be combined to batched draw call
I see
Hi! I have a Vector3 that I need to rotate 90 degrees around another Vector3. How can I do this? I know I can multiply a Quaternion by a Vector3 to rotate the Vector3, but I have no idea how to do it
"Rotate around" as in Quaternion.AngleAxis?
Or rotate around as in the other vector as origin
Possibly, let me take a look
Yep, that's solid! Thank you ๐
Quaternion.AngleAxis(90, transform.forward) * vectorToRotate``` So this would work right?
I want to rotate the vectorToRotate 90 degrees around the objects forward axis
If vectorToRotate is relative to the object then sure
Perfect. I figure I can just add vectorToRotate and transform.position after?
Yeah
Thank you so much ๐
can I force passing a struct as a reference into an object type field?
ref
wouldn't you have to have ref on the other end, on the parameter?
or the struct, i forget
that's an external tool sadly, I'd rather avoid modifying its code
I can modify the struct though, how?
what's the error
What are you trying to do
If you want to cast struct to object, you have to box
oh right you've no typing on that
I have a dependency injection tool that is meant to use classes, but works with structs most of the time
unfortunately, to inject an already created object (rather than creating a new one) I have to pass in the object as a reference, since I'm not getting it back (result type void). It's meant to be a class, so it's not much of an issue... except I want it with a struct
Do you have problem with just boxing it?
boxing it how?
Just call it
Oh you mean you are injecting into struct?
That's pretty much not possible area unless the your DI container API supports it
It works, when I'm creating a new object through the api, since the injected object is returned
that's actually a big reason we moved to zenject in the first place
the issue is that it doesn't get returned if I'm trying to inject an already-existing object
I mean populating to exiting struct
Actually you can.. eh
object copy = this;
Inject(copy);
this = (MyStruct)copy;
Could try something like this
What if you did like some generic class wrapper and just passed the struct in
uhoh that looks not good but I could try...
I mean I guess that's technically boxing it too
can't wrap it, because then it won't get injected, the wrap will get injected instead
and the objects contained within the wrap won't get injected
which is rather sad but adding that functionality to zenject is way above my paygrade lmao
I have used a homegrown solution before, but that was too simple and too costly to expand
we had to rip it out and move to zenject because it was just too much work to maintain our own
ok, it was relatively advanced, but it had a million problems and zenject, most of the time, just works
zenject is a bit complex yes but also very powerful when you figure it out
hello everyone
how to make the parameter on my method become dynamic?
so it send the info of the clicked button
Making it too powerful often ends up weird pattern IMO
wdym?
I mean it's like C++ ig, it lets you do about anything
So it is kinda easy to mess up if you code without caution
I worked in C++ a while, I really wouldn't make that comparison XD
seriously, I have not had problems with it at all
What do you mean become dynamic
i made a parameter on my method of type " button"
when the player click one of these buttons i want to know the button clicked become the one in the parameter
sorry i mean i want the clicked button as the parameter button
never mind i did it the hard way ( it is not hard but i want to know the easy way for my info)
https://pastebin.com/drVDHZsE
I'm stupid or this is far more complicated than I gave it credit for. (Or both!)
I'm trying to get my AI to simply walk around a wall, stop within it's attack range, face the target (core) and then shoot. It sounds simple, no?
For some reason it walks around the wall, runs all the way through it's target, then faces the target (core) then shoots.
I'm so lost, I can't find a reason why it's acting like this although hopefully it's obvious to someone else. I'm on hour 3 trying various fixes, reading the navMesh API and I am just at a loss.
Help appreciated, thanks in advance.
Note that my enemy (The AI this is attached to) is set as a kinematic body.
Have you attached debugger and see if the code working as intended?
I've littered the code with debug.log statements if that's what you mean. It doesn't enter the else if() portion of the update function until it fully runs into the core for some reason.
My thought process is since this if statement is asked every frame it should update pretty much instantly when it's within the attackRange and stop moving via the second part of the code. The issue is that it's just not getting into that code until it's well past that point.
If debugger is a unity tool, I'm unfamiliar with it.
You'd want to get familiar with it, it's your best friend
This sounds wonderful. Where has this been my whole life?
Also I just commented out after else on line 50. That seems to have worked... I just overcomplicated the function it seems. ;-; I only thought to try that because of my reply to you so thank you again.
To create trasnparent bullet holes in a mesh, would some sort of texture mask or shader be the best option?
modifying actual geometry seems.. expensive
Yep, usually bullet holes are just decals of some kind. If you need them to be truly transparent, you could write a shader that samples from a 'damaged' texture and clips the bullet hole areas
what do you mean, transparent? are you trying to say, conventional bullet holes, like in every other game? or are you trying to say, the hole goes through the mesh, and now you can see through it?
you have to declare a new class and set the struct to be a field on it, then inject that.
that won't work
i guess, why is it a struct at all if you need to inject it? just make it a class
struct --> class
yeah I ended up doing that, but it doesn't really fit for it to be a class
but whatever
@polar marten Yeah I want holes in my craft. This is in combination with the combined meshes from earlier. Goal is to build something out of some hull bits, merge such said thing into a mesh, put things into that mesh, then figure out some ways to represent an interesting damage state. Possibly with a combination of texture level stuff and if enough damage, maybe have things break in half using some mesh deformation....
It's.. a lot
what is the look of the game you want to make
is the purpose of the game to have a destructible spaceship?
is that the game?
you might like mudbun https://assetstore.unity.com/packages/tools/particles-effects/mudbun-volumetric-vfx-modeling-177891?srsltid=AfmBOorU4vX8E6Jf8ROZ1dH3D6tgipPavohxfdWsGM-g4DyTnuy7DNcL @compact spire
there's stuff that's more mechanical and sharper. you are looking for CSG assets. there aren't many though
you will also need a package called "vhacd" to create rigidbodies "with holes" (i.e. multiple rigidbodies of the correct mass)
@polar marten More like from the depths.
Build all manner of craft, have them fight
Well FtD ships are built out of a thousands of simple shapes, and destruction of the shape shows the damage. Elegant, but I'm going with scaleable shapes instead
That have a volume that you put things in
volumetric vfx... hmm
that seems like a completely different kind of direction
When you do something new, you have to consider why nobody else has tried the idea so far. There may be reasons why it can't work in terms of complexity, design or effort. Often when something new comes about, its design, workflow and technical implementation are very dependent on each other and it is very unlikely that it can be achieved with off-the-shelf tools.
@cold parrot That is fair, I feel that it's doable, it just depends on how many compromises I'm willing to make on my idea.
I'm just prototyping right now
I prototyped the building system as far as I need to, to get a feel how it's going t go
now I'm looking into performance feasibility for the physics and other interactions
what is the fundamental fun part of the game?
Building your fleet of craft and then having it fight.
trying to scratch the same itch as From the Depths, Avorion, Stormworks ect
so "assemble stuff and watch it explode"?
There is more beyond that, but that's the root of it
and how are you innovating and enhancing that?
Those mechanics specifically? Different building system
i mean, why is your system more effective at scratching the itch?
Less complex/ more efficient building system. Easier to build what you want. More of a focus on something a bit more rounded than FtD/Stormworks
will it also be prettier?
I don't know. It should end up looking better than FtD
do you have maybe also have a stronger narrative or thematic hook?
Stormworks has a clean aesthetic that I'm not really going for
narrative and theme are outside of what I'm prototyping
so are there predefined modules that you kind of assumble into a big warship?
Sort of
Imagine a lot of basic shapes, but you can scale them to make a hull
the hull has volume that you fill with things
I'm not sure I'd bother with stuff at decal scale then. I think you'd want to predefine some 'fracture lines' in each shape and then decide how to break them based on incoming damage
I'm playing around with mesh skewing to get even more customization out of the shapes
Well, i find this kind of game very interesting to make, but having made such a thing recently (a building game), its just a huge mountain of work. I would aim to keep stuff as simple as possible and search for a really strong twist on the basic idea that does not require you to have 1000s of build options, but as you said, thats basically what your innvation is, so it think thats a good one.
whenever I try to design a ship-based combat game I get stuck on that the fantasy is really strong, but in practice, ship combat is actually very slow and binary in a way that makes it not very fun to watch and only marginally fun to participate in.
i would expect that if you make more free-form and rounded, non-grid, or not hotspot-snapped shapes you will explode your complexity
@wicked scroll have you played From teh Depths?