#archived-code-general
1 messages ยท Page 338 of 1
if the sprite is close to ground it dont render
if its farther away it can render
weird
they look like they're all at the same height to me so I'm not sure what you're talking about.
again it looks like it's due to the clipping planes on your camera.
You're talking about the strip at the bottom of the game view where the object is not visible?
That's definitely the near clipping plane
which sprite are we talking about?
the grey slime looking one, barely visible near the UI at the bottom
it would help if you explained what that object is
show it's inspector
etc
"sprite" isn't really a thing.
SpriteRenderers
UI Images
MeshRenderers
THese are actual things^
Sprite is just an asset in your project folder
Is it not just no longer in view of the camera?
with what sorting layer/order in layer?
If you disable the ground is the other thing behind it?
default
gonna check rn
if they're both default then you're in the wild west
You need to set their sorting layers/orders in layer if you want to control which object appears in front of the other for SpriteRenderers
im just gonna try making the ground instantiate 3d objects to use as ground instead
nevermind i have no idea how to get the gameobject i instantiates
trying mesh rendering
Instantiate returns the object it creates, of course
i mean the gameobject of the tiles
tiles can instantiate objects
but i got it working it think
i changed the rendering layer as i noticed i wouldnt actually have caves etc
Is Physics.Raycast unreliable for registering clicks on an object this size on your screen?
Once I push the cube to about this distance/screen size, the raycast stops being reliable... even though my cursor is still enveloped by the cube.
I'm doing this:
Ray ray = mainCamera.ScreenPointToRay(Input.mousePosition); RaycastHit[] hits = Physics.RaycastAll(ray, Mathf.Infinity, snappableLayerMask);
of course it is reliable
I thought it should be... not sure why it's not working
might be something else going on
what exactly you expect to happen with clicks?
also worth checking Debug.DrawRay with longer duration
Well I have Input.GetMouseButtonDown event, and I'm reading Debug.Logs. When it "doesn't work" I don't get any Raycast hits
could you share the full script
void Update()
{
if (Input.GetMouseButtonDown(0))
{
MouseClick();
}
}
void MouseClick()
{
Ray ray = mainCamera.ScreenPointToRay(Input.mousePosition);
RaycastHit[] hits = Physics.RaycastAll(ray, Mathf.Infinity, cubeLayerMask);
foreach (var hit in hits)
{
Debug.Log(hit.transform.gameObject);
}
}
So, sometimes I get the Debug.Log results, sometimes I don't
I'm always clicking on the same object btw
yeah don't see anything that stands out here, do try drawing the ray each time and see where it is when its not detecting , you never know
Debug.DrawRay(ray.origin, ray.direction * Mathf.Infinity, Color.green, 2);
Thanks, I've always gotten confused by Debug.DrawRay the few times I've tried using it
Well, what the heck, the DrawRay' isn't showing, and I have Gizmos turned on ๐ฎโ๐จ
did you get it to work
nop
can i see the code
it's exactly what navarone shared above. i put that line inside MouseClick method and I even tried putting it in update but nothing
can i see the OnDrawGizmos()
i dont know what that is
where'd you put the drawray?
I answered that above
you cant Debug.DrawRay() outside of the OnDrawGizmos() function
yes you can
fr? ๐ญ
anyway i might just go back to the drawing board tomorrow because this is stupid. never thought clicking stuff would be the rabbit hole i wasted my evening work hours on lol
have you confirmed that your code is actually running?
this shit woulda helped me so much
i was trying to get something like this to work for my game too
the elevator intro sequence where the buttons where clickable but 3d
yeah. it'll work most of the time, then randomly it's like the colliders stop lining up where the cubes are. i've been noticing when that happens, if i click to the sides of the cube, it often starts working again
but when i go into gizmos and check, they're perfectly aligned with the cube so idk
How can I change gamma amount via script in HDRP? I can't seem to figure out how to access the LiftGammaGain override. This is what I attempted: https://hastebin.com/share/cufifuleha.csharp. But this isnt setting the gamma amount when I adjust my UI slider, is the gamma variable a copy of the one I am trying to access?
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Gizmos.Draw[shape] needs to be there. Nothing in the Debug class needs to he
whats the difference between gizmos.drawray & debug.drawray
OK yall don't hate me for not thinking of this sooner, but my MainCamera was originally a prefab for Meta VR. I just swapped it for a vanilla camera and clicking seems to be more reliable now
Now I can go to bed less frustrated. #winning
does unity have an ID for every Object such a texture's that is persistent across runtimes?
yeah, try looking in your .asset/.meta/.scene/.prefab files
how can i access via script?
they're in yaml
you shouldn't, it's for unity to use. use references that unity exposes to you instead
I think perhaps they mean why not make a reference in a script, drag the texture in via the inspector, then reference that when you need it
I'm still stuck on this, I can't figure out why the gamma isnt being set.
I've tried switching to using gamma.gamma = new Vector4Parameter(new Vector4(value,value,value,0));
That changed nothing
I am building an android project. But the buttons doesn't work at all when I try the build in a phone.
I've tried unity buttons, (custom) event buttons, Input System On-Screen Buttons. Still doesn't work on phone but works fine in editor.
version 2022.3.29f1
maybe #๐ฑโmobile can help better
okk ty
Hi guys I wanna make some sort of "smooth" movement, it's originally done by simply moving x% to the target position constantly...
But it's not working well with time, or more specifically, the framerate
Does anyone know how to make it framerate-friendly?
I tested smoothdamp and it's not what I want at all, the speed feels too even...
Eh, one obvious way is to put it in fixed update ofcourse, but any better ideas?
Show your code. But normally you make it frame rate independent by multiplying by time.deltdatime.
lol no
Cus moving the vector from current to target position multiplied by 0.02
Will mean that if framerate is high, it will simply move many more times than it's supposed to
0.02 is fixed delta time. Not deltaTime
If you use deltaTime in update, it will be independent from frames, cause the deltatime changes the higher or lower the frames are
But multiplied by deltatime instead means that if you're lagging for example and accumulated 0.5 as deltatime, you'll instantly move half way
what else do you want? This is frame rate independent behaviour as you asked for
K try moving 0.2 5 times or moving 0.5 2 times
You dont understand update and deltaTime obviously
Moving the offset * 0.2 will be significantly less distance
We're talking about an offset that changes each frame ๐คฆโโ๏ธ
Each time you move, the offset changes
yes it is the same thing. So what do you actually want if not for frame rate independent movement. Btw unity has a max delta time https://docs.unity3d.com/ScriptReference/Time-maximumDeltaTime.html
you are saying you want frame rate independent movement but now you dont because it may move more at one frame.
Geeez no
If you multiply by deltatime, you'll end up far less the higher your framerate
If you don't, you'll end up further the higher your framerate
than you are using it wrong
OFCOURSE
you're using deltaTime wrong then. Or somehow you're a genius and every game out there needs to be fixed
Like I said, show your code....
yeh, lets step into some code instead of theorizing ๐
transform.position += 0.02 * (targetX - transform.position.x) * Vector3.right
For example this
I just want a movement where they do a burst and slow down the closer they are
show the actual code you have, rather than examples. No point in obfuscating because this is clearly wrong
var spriteAssets = TMP_Settings.GetSpriteAsset();
var spritesInfo = spriteAssets.spriteInfoList;
Debug.Log(spritesInfo[0].name);
Debug.Log(spritesInfo[0].sprite);```
why do i get the name but null for the sprite?(its the default TMP sprite asset
If you multiply it by deltatime, in 1 second:
If there's 2 update calls of 0.5 deltatime, you'll end up at 75% of the way
If there's 1 update call of 1 deltatime, you'll end up at 100% of the way
If you don't multiply by deltatime it'd obviously move faster the higher the fps is
There are literally 3 people telling you the same thing, and your adamant that we are all wrong.
Yes, might as well go test it out if you don't believe me.
Copy that code and try it at different framerates.
And even worse, lol no facepalming and geeez noing our comments.
Good luck with it, making something frame rate independent is one of the first things you learn in Unity.
Why are you in here asking for help if you ignore the help
You are wrong, I already read your code.
Im not sure how you're confused here. You asked for frame rate independent movement. So maybe you should stand up and consider this with a real life example.
Wait 0.5 seconds, take a step. Wait 0.5 take another step.
2nd case
wait 1 second, take 2 steps. Woah magic u are at the same place ๐คฏ
this is literally basic multiplication
0.02 is not delta time.
You are hard coding 0.02, people are telling you to replace that with delta time.
If, let's say, in 1 second you're meant to have moved 99% to the target
That's framerate independant, right?
Now, if you don't multiply by deltatime, and move 50% each frame
If you update with 1 fps, you'll end up 50% of the way in 1 second
If you update with 2 fps, you'll end up 75% of the way in 1 second
If you multiply it by deltatime, then:
If there's 2 update calls of 0.5 deltatime, you'll end up at 75% of the way
If there's 1 update call of 1 deltatime, you'll end up at 100% of the way
this was never mentioned as your goal, so now back to this point. #archived-code-general message
you've obfuscated your ACTUAL problem
the code you shown and this last problem are completely different
They're the same thing
The code I show move a certain percentage per frame
And it's useeed... Lemme fetch the recording
The movement of the enemies
Notice how they move quickly but slow down as they approach the target? Yeah I want it to be moving by bursts '^^
That's the reason for all this...
SmoothDamp nor lerp does this kinda bursts...
And the only way to make it work correctly is to update during FixedUpdate, as it has a constant framerate
FixedUpdate doesn't have a constant framerate, it's not used for frames
Ooops this recording is wrong, it runs faster on pc
Or... Uh, oh, must've been the recorder bogging performance down too much
you werent even using deltaTime in that code, but really no ones staring at that 2 minute video to try and see what you were referring to.
In simple terms it does
You would just set up a curve and lerp between start time, end time, and current frame time.
if you're hardcoding 0.02 in FixedUpdate you should use fixedDeltaTime instead
There's no need for any of the frame rate shenanigans.
Hmmm... Well, true, that actually works indeed
Although I think that it's probably inefficient to compute a curve instead
But thanks anyway... Sorry about the outburst tho
As for your question... I've shown my original code.
I mentioned both delta time and smoothDamp, you actually want them too?
Modern CPUs run billions of cycles per second, plugging a value into a math equation is nothing.
Better to do it right than worrying about non existent performance problem.
In fact I can post every way I tried... If you're really interested in those
hmm what happens if physics can't run at its fixed rate due to hardware or performance issues
no i misunderstood, i thought your video was trying to show the issue when u used deltaTime
itll try to play catchup up to a certain degree. but theres a max delta time so you really cant run a whole second of game logic in 1 frame i believe
Pretty sure fixed update can accurately be simulated by Update, you just need to keep track of last update time/remaining time before next fixed update
FixedUpdate is basically execute for every x amount of time passed
Thats why there are minimum system requirements I guess
Quick question, but can public methods still be called from a component that's disabled? Not the game object, but just the component.
If its disabled, its disabled and wont run
I'd like to disable the component just to stop the Update loop on it, but still access some Raycast methods on it
Why not introduce a boolean in your update to not execute anything
Because that's still running a loop
An empty update()
you can still call your component methods
disable is just telling the engine dont handle your component
Thanks, that's what I assumed
Just be sure that its like a method thats not async or coroutine or whatever, cause those wont run
no
nothing? If you dont do it on update
Nothing particular. It's how you use it that might be a problem.
There is no issue in using getcomponent in start
It's not what's wrong with it, it's dependant on how you're using it.
If you're using GetComponent quite frequently, it's very expensive. But if you're using GetComponent once and caching it, it's perfectly fine.
directly referencing the component if you can. If the component is on the same object u can drag it in with a [SerializeField]. You cannot avoid it if you are trying to get a component on a completely different object. Like a projectile trying to get access to some health script on a character
You could do this, but you can also just have a direct reference
Well, it's mostly because using a serialized field is more convenient. It's really a lot about preference though.
One minus I can think about is that if you're using it to initialize everything, that might increase your scene init time.
Assuming you're using GetComponent to get a component that's on the same GameObject or even a child GameObject. You can 100% do this. But it would be less costly if you just use a Serialized field and directly reference it in inspector.
Great, that's a perfect example.
So in your PlayerCollision script, you can definitely do this:
private Rigidbody rb;
private void Start()
{
rb = GetComponent<Rigidbody>();
}
It's not that expensive, since you're caching it
But this is not a necessary cost
You could easily just do this
Keep in mind that C# code and Unity's context on components are two completely different things
A component can be disabled or even removed but the C# code will still be valid and exist
It will not exist if disposed or there are no more references, unless the code had static variables
The only thing disabling a component does is turn off Unity's event driven system where it invokes Update and all that
That's exactly what I want. I just want to stop update loop.
Does threading still work if oyu disable it, guess so, right?
You could completely destroy a gameobject but still use its scripts if you had some reference to the game object basically
But obviously this is not a good idea
Correct. Although it's bad practice to use public variables unless necessary. You should be doing this:
[SerializeField] private Rigidbody rb;
public variables can be accessed and modified from other scripts. That can be problematic.
The point is encapsulation. Keep everything as inaccessible as possible until it must be more accessible for some reason. It keeps your code clear.
Is your question how to reference the player for this?
Yeah, that's a bad way to do it
Because you'd have to use GetComponent on every single collision in that instance
you could for example use the oncollision methods to get the other collider or you could have a static reference to the player.
you would likely GetComponent here, because you cannot drag in the player to every wall. Also doesnt work if you're spawning the player at runtime. Otherwise you would be relying on like a singleton but its not really good to just have a shitton of singletons
You should be doing it the reverse Dread
also u dont need to GetComponent on every single collision. U can use layers to ignore everything else, put your player on a layer which only characters are on.
Use it to setup
Do the collision event on the player
Because you don't need to search for a rigidbody in that case.
Assuming your game only has a single Player, then what you can do is implement something called a Singleton. See the Singleton explanation here -> https://unity.huh.how/references
Using a singleton is an easy way of referencing something that only has a single instance without using too many static references.
Yep yep, I know ๐
if you use a singleton then you can just store the component in the player class
When you have something a little more dynamic and you're not sure what exactly the object is
Or when you have more than one player for example
But in all the examples you gave, you already know what the object is.
Collision events is a good example when you might want to use get component
creating players from one prefab but with the same script would share static references for all players. you dont want that to lets say modify the username or something
this is situational, and arguably worse. I know its an example, but sometimes you end up with cases where you dont want this logic to happen with every wall. Then you start needing to adjust the walls, and the player script which is completely unrelated.
Like if an enemy AI wants this logic too, it either needs to add the same logic, or you move the script to the wall.
I kept it simple for his example. There are edge cases in everything. The point was that one is less expensive computationally than the other.
No, you can still modify if you direct reference
Yep
And my point is that you shouldnt throw scripts on different objects to avoid GetComponent. GetComponent is cheap and as i also wrote above, you can use layers so it only tries to GetComponent on specific objects. Like if there is a character layer, theres a pretty high chance its got the script they want.
In his specific example, there is literally no reason to use GetComponent.
I'm not saying there aren't cases for it
But it's objectively slower. Again, in that specific case.
Collision in general can be very complicated, so I agree with what you're saying @lean sail
your movement shouldnt really be using collision events. It may not be an issue if you're just using standard RB movement but for sure doesnt work otherwise. Usually you'd want raycasts/capsule casts
You can to set your rigidbody to Continous or Continous Dynamic to fix that
Then you will still collide at high speed.
No matter what you do, at high speeds you will get unexpected results. If you expect to go decently fast, swap to physics casts
even with any of the rb settings
The more you do it, the more you'll figure out cases for it ๐
In general, it's not that taboo if you use it.
Only if you use it frequently
Nah, you can serialize the rigidbody here too
you will get compilation error
You will get complications
You can't define rb in Start method and use it in Update.
Should be like:
public class Enemy : MonoBehaviour {
[SerializeField]
private GameObject explosionPrefab;
private Rigidbody rb;
void OnDestroy() {
if (explosionPrefab != null) {
Instantiate(explosionPrefab, transform.position, transform.rotation);
}
}
void Start(){
rb = GetComponent<Rigidbody>();
}
void Update(){
if (rb != null) {
rb.AddForce(Vector3.forward * 10);
}
}
}
But you can also do this:
public class Enemy : MonoBehaviour {
[SerializeField] private GameObject explosionPrefab;
[SerializeField] private Rigidbody rb;
void OnDestroy() {
if (explosionPrefab != null) {
Instantiate(explosionPrefab, transform.position, transform.rotation);
}
}
void Update(){
if (rb != null) {
rb.AddForce(Vector3.forward * 10);
}
}
}
Optimization nitpick, but if null checks are a bit expensive too >.<
Wat. Null checks are NOT expensive
Unity support for both ReSharper and Rider. Contribute to JetBrains/resharper-unity development by creating an account on GitHub.
we all have lines of code in our project that test whether it's something is null or not, so which way is best to get the null reference?
๐ฅSimple Trajectory Prediction 3D/2D Unity - Without LineRenderer - Perspective and Orthographic: https://youtu.be/sDFCHTIdSIw
๐ฅFlora Assets Review - Ultimate Vegetation Solution for Unity - Render millions ...
Ok, and still it is not expensive. Of course it is worse than not doing it at all
When I say "expensive" I don't mean it's going to take several seconds to compute. We're talking milliseconds of difference haha
anyone mind helping me in #๐ฑโmobile ?
But fact is that it is slower and it can potentially add up.
Not even milliseconds. This is not something that can add up. You arent doing thousands or more of this at once ever.
This is not even nitpicky, it's just wrong.
i wont check if it is null if it must exist
Which part is wrong?
missing it is a fatal error, just stop the application and check
computers are fast. a single operation like that would take nanoseconds, not milliseconds
Fair
stuff gets worrying when you have millions of those operations, then it can add up to milliseconds. that's what benchmarks and profiling are for
Wrong to even suggest it as an optimization. It does not even take milliseconds. Your focus is completely on the wrong target. Optimization should be only looked at after profiling. If you're running enough such that a null check is costly, well the logic you're about to do on those unity objects after are gonna be horrendous * 100.
This is like saying "my program slows down when I add 2 numbers, 100000000 times." The question is not how to speed up addition, it is how to reduce the amount of logic you're doing.
which is what this rule intends to do, it reduces the frequency of checks, it's not just trying to remove them altogether
Maybe I didn't explain myself properly, but that's exactly what my point was.
yeah, it wasn't clear what exactly you were proposing
i'd remove it regardless of any expense though tbh. let it be an error so it isn't a silent bug.
If your point was just "it's more expensive compared to not doing it" then that can be said about literally anything. But you did explicitly say it is expensive and linked resources about it.
There are cases where u do need to null check, but it isnt something I commonly do either
I do null checks literally all the time. It's necessary in cases.
But I don't consider it necessary at all in the above case. And because it's unnecessary, I do consider it a meaningless expense.
But that's just me
Then don't check for it every frame and determine if rb is set in Awake if it's a vital part of your code
Seems pointless to check something that won't be null unless there is undefined behavior
Also, it was already mentioned, but a check like this makes a nanosecond difference. Please don't do optimizations here
Always do null checks for things your use that are set publicly. I'd argue it's optional when you talk about private data since these are unlikely to be set to null by accident
This is exactly what I think
Also
One way to check if the state is still valid is with Debug.Assert
Your IDE will call a breakpoint on it if the boolean predicate returns false
And this is purely for DEBUG, so builds won't have it (assuming you build in RELEASE mode)
I usually add these in private code, and use proper if-statements in anything public
What resource?
Can you show what you mean?
Different materials that use the same shader should usually get batched together
@swift falcon Please write in full sentences
line1
line2
line3
well, Shift+Enter is a thing. Also #๐โcode-of-conduct
anyone mind taking a look at #๐ฑโmobile
You should post the results of the search you did and what you've already found about it.
And then post the error in plain text so others can do a more thorough search if you failed to find anything
ive only found results relating to other things
nothing on my specific problem
im still looking for anything relating to my problem
the animator has a GUI which it uses to define a graph for how animation states play into each other. then you use code to set animator variables, and the animator component swaps to the right state
you will need a tutorial
can anybody help me with my code??
for some reasons gameData is null when SaveGame method is being called...
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.
It's a [System.Serializable], it is working before, but it for some reasons stopped working
alright, thanks so much. I've been stuck with this bug for a whole day now... I couldn't progress t all
You creating it in NewGame() , which I suspect is not being called anywhere
Are you getting an error or just your log that is null? Looks pretty safe otherwise - trying to determine where it might have gone wrong, if it had.
none
the problem is, I get this error when I use the Save method
looked through it and
looks like "data" is showing null, that's why I couldn't pass staminaBar.value to it
no...
did you check or are you just assuming?
if I placed
if(data != null){
data.stamina = staminaBar.value;
}```
it skips stamina and proceeds to my moneyManager, which also has "SaveData"
Well, you aren't handling it if it's null cs public void SaveGame(string dataFileName) { if (this.gameData != null) { Debug.Log("Gamedata is null at DataPersistenceManager"); } foreach (IDataPersistence dataPersistenceObj in dataPersistenceObjects) { Debug.Log("Pass: " +dataPersistenceObj); dataPersistenceObj.SaveData(ref gameData); } dataHandler.Save(gameData, dataFileName);//game data was null }
how do I fix that?... I swear everything was working properly until it stopped working
The messed up bandaid solution would be not letting them save if the game data was null ๐ฅน cs if (gameData == null) return;
GameManager script?...
Please properly share your !code
๐ Large Code Blocks
Use 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 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.
ohhhh
Can you share the contents of StaminaManager.cs?
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.
the thing is, if I removed the save in StaminaManager.cs it will error on other managers (timeManager, moneyManager) etc.
Is the Debug.LogError called on line 18?
no
It is unclear what exactly is null here
Can you log data and staminaBar inside that method, and see what is null?
Then what calls SaveData? please share that
Also, if GameData is a class then ref is not required to be part of the parameter
SaveData is interface used by other scripts to save the game like:
and the error is right there at data.stamina = staminaBar.value; because data is null
So then the issue is that whatever calls this method passes a null reference
So you should make sure it isn't
Or share the code and I can also look
it strings off to here
which one?
Your if-statement is reverse
It should check if(this.gameState == null)
Not that it would fix anything but at least the logging works
Oh, you have the check twice
I did.... XD
Is there a method that implements SaveData and sets data to null by any chance?
Considering you pass ref, this means it is eligible for reassigning
Perhaps you should just get rid of the ref altogether
It makes no sense to have that there
How does this help?
Your code isn't even valid because the behavior works with multiple classes implementing the interface, not a single one
That's not fixing the issue of the variable being null
uhm, the whole DataPersistenceManager.cs will collapse if I changed the SaveGame to that
It's likely a reassignment in one of the SaveData methods because ref is used
Hence why I wonder if removing it would fix the issue
One thing you can also do is put Debug.Log(gameData) before SaveData to see when it becomes null
@hasty wave
I'll try
the same place where I get confused, why is gameData not null outside but null when SaveGame() is called
No, put it above SaveData, in the foreach loop
Just a simple check, no if-statement
foreach(...)
{
Debug.Log(gameData);
dataPersistenceObk.SaveData(ref gameData);
}
Like this
Wait, so it is null in general
Then why did the previous code have a proper if-statement that would prevent this, and now it doesn't?
No wonder it's confusing
So where is gameData assigned? please share the whole manager
see what I mean?...
I don't get it?..
My point is that you have a proper guard clause here: https://discordapp.com/channels/489222168727519232/763495187787677697/1252599779821748386
But now it's gone
So the code here properly handled the null check and logged an error
So either you return; in the current if-statement, or you fix the issue where it's not assigned
And as far as I am aware you haven't shown where you assign it so idk what the code does
checklist?
- check that gameData is initialized in GameManager
~~- staminaBar is assigned in the Unity Inspector ~~
- add null checks and debug logs in StaminaManager's SaveData method to verify that both gameData and staminaBar are not null before accessing them
~~- check that StaminaManager is attached to staminabar ~~ - make sure gameData is initialized in GameManager.Awake() and make sure references are correctly set up
This is not helpful in the slightest
@hasty wave Please share the code that assigns gameData
I.e. the method and relevant field/property or the whole manager. The latter is more convenient
DataPersistenceManager: https://pastebin.com/f9mvQT9K
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.
What is dataHandler.Load? What does that do?
is there a way to refresh a gameobject? in our project I've made a blood system that paints blood onto a rendertexture to be used for masking in shader graph. we have 60 floor tiles that all use the same material but in code all create their own "blood mask" und assign it to their material. if I bleed onto a tile some other tiles randomly will also show the blood splatters (only from certain angles and it flickers) and once I open the material of the bugged floor tile its like the mask texture is refreshed and from then on actually uses the texture given in code instead of randomly using one from another tile. idk if this made much sense but I basically need to open the material tab of each floor material to refreh its mask...but not manually obv.
which line?
it loads the data
Log loadedData for me just before the return statement please
I am guessing you have fallen victim to the shitty JsonUtility parser
Either that or the file does not exist, so it returns null
Does it never return null?
Maybe a better check would be to see if it is returning null, because the code is not supposed to return it judging by your code?
Or maybe it should return an empty GameData object if it's returning null?
I mean the default is null
So if the file does not exist, or deserialization failed, it returns null
And your manager relies on a valid object, not null
how do I fix this issue?
An easy way is changing return loadedData to return loadedData ?? new();
It will assign an empty GameData object when returning null
Or to correctly handle this method returning null
An easier syntax is this:
if (loadedData != null)
{
return loadedData;
}
return new GameData();
I don't understand what does this do?
But as Fen mentioned, your lack of proper nullabillity handling is the bigger issue here
I would rather not have a "load save data" method return a valid-looking (but empty) game data object if it fails to load something
See the easier syntax above
this and that does the same thing?
You should probably use the easier one
Especially in Unity it might actually do something different, it's a complex topic
In this case, yes, they are exactly equivalent.
Destroyed Unity objects compare equal to null, but aren't actually null.
omg it finally worked! thank you so much! ToT)
okay!
destroyedObject ?? new GameObject(); // will give you destroyedObject, even though it compares equal to null
missingGameData ?? new GameData(); // will give you a new GameData object
Please take some time to read about nullabillity in C#. I think this article is pretty relevant https://wildermuth.com/2023/02/13/nullable-reference-types-in-csharp/
This topic has been on my TODO: list for quite a while now. As I work with clients, many of them are just ignoring the warnings that you get from Nullable Reference Types. When Microsoft changed to make nullability the default, some developers seemed to be confused by the need.
There are pretty good ways to make sure you don't fall victim to NullReferenceException issues
It's a very common issue
I will! after all that happened I'll read it throughly, thanks again so much for the help
Especially in Unity which (I think) still lacks proper nullabillity support, but the article explains how to enable it
Glad it works now ๐
sigh
Also, please still get rid of ref. It is not a good idea to use this
why tho??
there's no reason to use it here
for a reference type, all that ref does is let the called function reassign your variable
it doesn't really achieve anything else
ref is a way to pass the parameter directly instead of by reference/value. It only makes sense to do this when code directly modifies parameters, or require a reference from an otherwise value type
In your case, you set the content of an object reference and not the reference directly
It could make sense if GameData was a gigantic value type (a big struct)
but it's not!
oooh alright! thanks gain! :D
Is there a way to access or rather set the emission property of a material through code? I would like to make a script that turns that emission on or off.
if you set your inspector to debug mode and select the material you can see the real names of all the properties in the shader
From there you can use e.g. https://docs.unity3d.com/ScriptReference/Material.SetFloat.html to set whatever property you want
Ohhhhhh thanks, thats a really good tip!
Right, that worked perfectly, now the question is for objects with multiple materials, how do I access all materials and not just the first one in the array?
well, you'd iterate over the array
How though? I believe this code only returns one thing and not an array.
even when i set material as an array it doesnt accept it
see the materials property
I'm confused about a bug in this part of my game-
https://pastebin.com/ppz4Lhk0
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.
When playing on android, on initial launch of the game, the inputType is shown as "Touchscreen"
But it behaves like I'm actually using "Mouse"
And then if you relaunch it, or reload the game, it will actually be shown as "Mouse"
Oh I didn't realize that was a thing, thank you very much, thats the second time you have helped me now! You're a legend!
Maybe I made a mistake and isOn doesn't trigger the events linked to the toggle?
But then I crashed with an infinite loop before cus of it... That's why I assume it did
setting isOn on a toggle causes a change event, yes
you can use SetValueWithoutNotify to avoid causing an event
Any idea why the ui have touchscreen active while it appears that mouse is active PlayerPrefs-wise?
It only happens on the first time the InputHelper spawns in tho, it's as if the initial playerprefs setting doesn't work correctly even though I don't see any mistake in this
how are you showing the input type?
Toggles linked to a togglegroup
They trigger SetInputType when clicked
The toggle group is probably running its Awake after InputHelper's Awake
I thought that it's somehow a latency in the initial setting at line 15 ~ 17
Why would it only go wrong at the first startup tho?
Literally every launch of the game afterwards works normally
Only the first time you launch it there's this bug...
hm, that would not be consistent with it being a toggle problem
maybe Input.touchSupported is false at the moment that Awake runs
But then the toggle do show the right results...
log the values of mouseToggle.isOn and touchscreenToggle.isOn before and after you set one of them
Which shouldn't have been the case is Input.touchSupported has gone wrong
Okay
as well as Input.touchSupported and the value of PlayerPrefs.GetInt("InputType") before and after you check if you need to initialize it
Eh, sorry, I might've been mistaken about the scope of the bug
It actually seems to happen whenever you start up with touchscreen as choice...
ah, that sounds more plausible now
I think I can guess the location of the bug now, it seemed absurd before
maybe something else is reading inputType in its own Awake method
or otherwise reading it before InputHelper is created
(although that'd cause the opposite problem: using touchscreen behaviors when you wanted mouse input!)
It doesn't
Or at least on the editor it functions completely normally
If you're curious to know- I found it, but it's really weird, I'll give it that
Whichever toggle you have enabled by default will be the one visually active, despite something setting isOn at some point (Probably before the toggles)
However the playerprefs do exist and stay
That's my observation on the editor at least, on mobile it seems weirder than that
But it does seem to work correctly after I switched both toggle off
It's possible that the ToggleGroup hadn't yet had a chance to start listening for changes
since you were doing that in Awake
Maybe...
Tbh yeah, normally these kinda things that link to other stuff are best left to Start
What could be the reason of headers not showing in the inspector?
Did you save the script?
Check if you have any compiler errors that prevent recompilation
there aren't any
What do you mean by works ingame? Are you saying that the Editor inspector changes during the play session?
no, the actual script is doing what it's supposed to do
it's just that the headers aren't getting displayed at all which makes navigating the inspector much harder in more complicated scripts
The inspector will not update if you've got errors or if you did not save the script.
there aren't any errors, and the script is saved
Try restarting Unity
I have restarted the project a lot of times, this isn't the only script that doesnt work
Did you disable automatic reloading in preferences to reduce load times between Visual Studio and Unity?
not sure what that has to do with the problem
the script is literally saved in unity and works properly, it's just the headers that aren't rendering in any script
That's got to do with the script updating in the Editor.
Do you have an editor script for it?
Because that could be the problem.
If you're using OnInspectorGUI.
If you've disabled auto reloading you'll have to import each modified script individually or reimport all etc
nope
again, the script is imported properly
as indicated by the thing working in game
and not having any issues except the headers
The play session can be an older session. It doesn't mean changes are being applied - hasn't been stated at least.
Try importing it in another project.
See if the headers show up.
it works in the build, it has worked for over 6 months that I have been working on it
Those are my best guesses. There isn't much else it can be.
alright, will try
thanks anyway ๐
Also is your inspector in normal mode or debug mode?
normal mode
Okay.
it does work in another project
there is an editor script though, which has a CustomEditor for Object
looks like it came from the FishNet networking library
it's a fallback one though too
it does seem to work when commented out for some reason
what seems to work, exactly?
Do you have NaughtyAttributes in this project?
my headers show properly now
I know that it adds a custom editor for all MonoBehaviours. I'd expect it to correctly draw [Header] attributes though
when what is commented out?
a class coming from the FishNet library, GameKit.Dependencies.Inspectors.EditorOverride
Sounds like this custom editor doesn't handle [Header] attributes then, yeah
and it applies to every single kind of unity object
yeah
I don't think commenting out a random class from a networking library is a good solution, so I asked about it in their Discord server
Hey, i am having trouble with my camera following the wrong object in unity. Could someone help me real quick?
ask your question
explain what you wanted to do, what actually happened, and what you've tried
in before :obligatory Cinemachine ๐
Obligatory "use cinemachine"
Ah dang, you were in before it!
so im trying to add a new enemy to my (very) small fps game that i just made, so i made another enemy in blender and i imported it into unity, then i made it a prephab and i put it as an enemy in my code, but when that new enemy spawned the camera locks onto it for some reason and i have no idea why. ive tried to delete it and put it back again and ive even tried a different blender file
you probably have a camera leftover from blender
thats possible? im going to check rn
yeah, that's likely
Be sure to delete the camera and lights from blender before exporting
you can declare them anywhere in the class
not just at the "start": you declare a new field in one of your classes
just don't put it in a method
Variables need types.
this is very wrong. compare this to what the above-linked page has you do
No, I'm not going to spoon-feed you the answer. The page I linked you to explains everything.
You can't just "stop learning" for half of the day
You don't reference variables. You reference objects (in the C# sense of "object", not GameObject). You can read their variables from your reference.
you've spent several minutes arguing with me instead of reading the page I linked you to, which teaches you exactly how to do what you asked about
Because spoonfeeding the answer means you'll be back to be spoonfed 8 times.
If you just learn to do it you won't need to come back
yes
I want to answer your question. The answer is provided in this page.
lol. feels
If I didn't want to help you, I would not have said anything.
No one is condescending. And they did help you
@swift falcon not the best attitude to have if you plan on getting help here..
Also "learning" would be part of working on things
there is no distinction between "learning" and "working". You learn as you work, and you work so that you can learn.
telling you to actually read something that might help you isn't "belittling"
very true though? hows that belittlement hough
having "timezones" for learning is weird..
there i said it
You were given the resources you needed and got upset and mean someone didn't actually write code for you
to me it implied exactly what I said, its natural to learn at all times of the day.
Well that is an incorrect analysis imo
Be nicer to the people helping you. That's what.
Don't jump to conclusions
Text can be read many ways. Assume the best
anyway. Point being no reason to take offense when you aren't directly fed an answer.
whatever lets move on
I'm going insane. My multiplayer lib works fine outside of Unity but as soon as i import it and start using it in Unity, weird stuff happens, like the clients never connecting to the server
this pretty vague tbh
Unity gets weird with multithreading - make sure you have proper exception handling.
Maybe i should copy the lib source into Unity so i can debug it
oh nvm
i'm targetting multiple .NET versions so i'll need to modify some things
A key thing is that you shouldn't touch unity objects from anywhere but the main thread
Also, Unity installs its own "synchronization context" https://docs.unity3d.com/2020.1/Documentation/Manual/overview-of-dot-net-in-unity.html
the only objects that get potentially touched in events are 2 Vector3
Iirc Vector3 can be used anywhere right?
But even then it doesn't do anything before getting connected
those are structs, and they don't touch any other unity objects, so that ought to be fine
(structs can be deceptive: they can have properties that wind up touching other unity objects)
see ParticleSystem modules
hello, is anybody able to help me with update the billing library for play store and unity?
got this huge warning 2 weeks ago:
We are introducing changes to the lifecycle of Play Billing Library and its associated deprecation timelines. Because you currently use an older version of the library, we wanted you to be aware of new key dates youโll need to adhere to:
By Aug 31, 2024, all new apps and updates to existing apps must use Billing Library version 6 or newer. If you need more time to update your app, you will be able to request an extension until Nov 1, 2024.
Learn more about the deprecation here.
Update before these dates to avoid a disruption in app publishing and updates. Publishing and updating apps that use Play Billing Library version lower than 6 will be blocked in Play Console on the dates mentioned above.
Next steps: More information on how to migrate to the latest version of Play Billing Library can be found on our developer website.
but im kinda confused, i tried updating the IAP version and re upload the .aab
i still get this warning though
how is this a code question 
there wasnt any other suitable channel i could find ๐

thx
It's good practice to organize cohesive units of code into methods yes.
If it is very short and will neve need to be used elsewhere
Vague question- depends on what you're doing. But usually you'd use Quaternion.RotateTowards or Slerp
It makes absolutely no difference at all except to readability
Favor what is most readable to you
Vector3.Slerp/Lerp will not behave correctly for euler angles
it really depends on what you're trying to do.
Using euler angles you get weird stuff
like if you want to go from angle 340 to angle 10
the natural shortest way is to rotate clockwise by another 30 degrees
using euler angles you end up rotating the other way
back around down from 340 all the way around the circle back to 10
one of many reasons euler angles are not good.
no
transform.rotation/localRotation is a Quaternion
eulerAngles exists only for occasional convenience
Quaternion.Lerp gives you a rotation that's between two input rotations. It should be used to linearly move from one rotation to another, or to blend two rotations
this is a simple way to do random spread, for example:
transform.rotation = Quaternion.Lerp(Quaternion.identity, Random.rotationUniform, 0.1f);
this moves 10% of the way towards a completely random rotation
If you want to apply a rotation, use Quaternion.AngleAxis
You give it an angle and an axis to spin around.
transform.rotation *= Quaternion.AngleAxis(90, Vector3.up);
this spins you by 90 degrees around the vertical axis
* combines two rotations
so you can do transform.rotation *= anotherRotation
the Quaternion methods make it very clear what is being done
for what
vs. directly manipulating euler angles
i mean, it's probably fine, but I almost never use euler angles directly
i use Quaternion methods to compute rotations
For moving diagonally up/right when pressing WD? You wouldn't use either one.
they were asking about rotating with WASD
float horizontal = Input.GetAxis("Horizontal");
float vertical = Input.GetAxis("Vertical");
Vector3 direction = new(horizontal, 0, vertical);```
For input, you might want to store the desired angle
yaw += lookInput.x;
pitch -= lookInput.y;
yaw = Mathf.Repeat(yaw, 360);
pitch = Mathf.Clamp(pitch, -87f, 87f);
var turnRot = Quaternion.AngleAxis(yaw, Vector3.up);
var lookRot = turnRot * Quaternion.AngleAxis(pitch, Vector3.right);
this is part of my player control code
WD implied movement to me, not rotation.
If you want the car to point the direction you're moving, you'd compute a vector for the direction you want to go
then rotate the car to face that direction
fun shortcut: you can just set transform.up = someVector
Ok then:
float horizontal = Input.GetAxis("Horizontal");
float vertical = Input.GetAxis("Vertical");
Vector2 inputDirection = new(horizontal, vertical);```
but it really depends how you want the controls to work
do you want it to be steering with AD and throttle with WS?
or something else
there are many ways to design a car controller
Well GetAxis will add smoothing automatically
beyond that, Vector3.RotateTowards exists and works fine for Vector2s
this is way overcomplicated
There are many errors here
float horizontal = Input.GetAxis("Horizontal");
float vertical = Input.GetAxis("Vertical");
Vector2 inputDirection = new(horizontal, vertical);
transform.right = inputDirection;```
but your logic is flawed
Then to add smoothing you'd add like Vector3.RotateTowards to the mix.
Why don't doesn't this code change anything about the textures?
public Image image;
public SpriteRenderer spriteRender;
private void Update()
{
DrawCircle(image.mainTexture as Texture2D, Color.clear, 256, 256, 12);
DrawCircle(spriteRender.sprite.texture, Color.clear, 256, 256, 12);
}
public static void DrawCircle(Texture2D tex, Color color, int x, int y, int radius = 3)
{
float rSquared = radius * radius;
for (int u = x - radius; u < x + radius + 1; u++)
for (int v = y - radius; v < y + radius + 1; v++)
if ((x - u) * (x - u) + (y - v) * (y - v) < rSquared)
{
tex.SetPixel(u, v, color);
Debug.Log($"set ({u}, {v}) to {color}");
}
}
Also doesn't work with Color.red. There are no errors or warnings. I can see the debug statements in the console. I expected at least the sprite to work.
silly me
thank you let's see
that works. So is the only way to use setpixel to modify the actual texture file?
there's no sort of like runtime image? Or I guess I'd have to diplicate it myself?
if you want you can duplicate the texture in memory and modify that.
sounds good ๐
Instantiate would do the trick
I'm messing around with vehicles, and I've run into a strange issue. My tow truck is slightly unbalanced, causing it to lean towards the back, but this also results in it trying to roll backwards, and I'm not sure how to fix this.
center of gravity mass maybe
your tow has a collider? that also contributes to the weight
You've invented a perpetual motion device!
I get that that's what's causing the inbalance, but I don't see why that imbalance should cause it to roll away.
lol, isn't it great
Unity's physics engine doesn't respect things like conservation of momentum/energy properly
it's optimized more for speed than accuracy
somehow it's concluding a net force on your thing probably between friction and the collison between the wheels and the body
I would also try adjusting the center of mass to see if that helps
(which you need to do in code)
You have created the troll physics magnet car
By the way, the physics that I'm using is with the same approach as the one in very very vallet https://www.youtube.com/watch?v=CdPYlj5uZeI which is probably affecting it.
A detailed look at how we made our custom raycast-based car physics in Unity for our game Very Very Valet - available for Nintendo Switch, PS5, and Steam.
BUY NOW!! https://toyful.games/vvv-buy
~ More from Toyful Games ~
- Physics Based Character Controller in Unity: https://youtu.be/qdskE8PJy6Q
- Instant "Game Feel" Tutorial: https://youtu.be/...
i enjoyed that video
yeah its problem with these raycast
really nice breakdown of the mechanics
i use the same thing for my scooter
also might need to rethink how you setup your colliders
I think the problem is that the suspension points in the up direction for the wheels, so when it's angled, then the force points slightly in the direction it's tipped, but I feel like the force should be in that direction.
I don't know if there's another force that should be conteracting that movement (possibly friction).
oh no, it's the other kind of troll physics car 
i guess it might help to look up why a tilted car doesn't roll forwards
i had same issue but mine would go forward cause i have more weight forward
this may be illustrative
yeah basically
The force should be the exact opposite of the ground's normal vector
It shouldn't be pointing along the direction it'd go if you weren't sloiped
That's a good idea, I'll probably do some research, but if it takes too long, I might just implement something where the force is in the direction of the ground's normal instead of the tire's up direction.
That's actually what you want, I think!
Oh I see that you just said that.
The force will be out of alignment with the vehicle's suspension
but the force gets applied nonetheless
you'll just wind up with a "bending moment" (i think) ((my sister is a mechanical engineer; i don't know this stuff))
imagine the extreme case of the car being tilted 90 degrees forward
I drew up a thing in paint to help think about it, and I think the problem comes from the fact that we are only applying forces to the car when in reality, the car is also pushing on the tires. So if we were accounting for the force on the tire, then the force along the suspension would be correct, but since we aren't, the normal will be more accurate.
I also haven't thought about it for long enough, but I'd like to think that it actually does cancel out and point along the normal.
The force won't get "bent" to be parallel to the suspension
that's the important bit
The part of the force that is parallel to the suspension will compress the spring, and the part that's perpendicular will just...well, in real life, it'd eventually break the suspension
(you can use Vector3.Project and Vector3.ProjectOnPlane to separate those two parts out!)
Yeah that makes sense.
and if it did bend, well...
It's much more boring now, but tada! ๐
it would work because of angles
๐
finally, my vague recollection of "troll physics" memes from 2011 comes in handy
any help please to fix this problem ?
private void Awake()
{
spriteTexture = Instantiate(spriteRender.sprite.texture);
spriteRender.sprite = Sprite.Create(spriteTexture, spriteRender.sprite.rect, spriteRender.sprite.pivot);
}
```Why when I run this code does the sprite get set a crazy distance away from its pivot?
please
check the actual extents of the RectTransforms of your buttons
dm me please
different spaces ?
oh wait thought it was UI
nvm
is your tool handle in Center or Pivot mode
nothing I think I fixed it
You probably want to copy over the PPU too
spriteRender.sprite = Sprite.Create(spriteTexture, spriteRender.sprite.rect, spriteRender.sprite.pivot, spriteRender.sprite.pixelsPerUnit);```
I had the constructor with a ton of arguments before, i didnt try with just the ppu added, let me try it.
can you show more of the setup
still no
it's something to do with the pivot, when I set the pivot to Vector2.zero the sprite is aligned so that the bottom left of the image is exactly where the pivot of the game object is.
im not sure why copying over the old pivot is screwing it up like that though
is it https://docs.unity3d.com/ScriptReference/Sprite-textureRect.html instead of rect maybe?
I can't tell the difference
oh maybe I ddin't think of that
no, same deal
doing this:
spriteRender.sprite.texture.texelSize / 2
```gives the same result as this:
```cs
Vector2.zero
```I feel like those should give different results.
Is there no built-in way get a sprite image of an empty grid cell (so transparent except for the square outline) ?
I'm trying to make a grid using ui
simple to make one
9 slice it
I figured it out. sprite.pivot gives the pivot in pixel coordinates, Sprite.Create wants the pivot in texel coordinates... so, the proper thing to do is:
new Vector2(spriteRender.sprite.pivot.x / spriteRender.sprite.texture.width, spriteRender.sprite.pivot.y / spriteRender.sprite.texture.height)
```I feel that that is a bit unintuitive.
i'm sure it is... i just have zero photoshop/image editing software experience and was trying to quickly prototype something
you can make it in paint
it's 9 pixels
WWW
WTW
WWW```
Well I guess paint doesn't support transparent pixels
W = white
T = transparent
or just find one on google
so annoying all these websites want you to make an account to download images
you'll want to use a pretty low PPU value for this
given that it is 3 pixels across
hmm thanks but that's just showing as a normal square
Just grab paint.NET and make one
you have to slice it
ok mission accomplished
โค๏ธ learning new skills kicking and screaming
Hi guys how can i make a cube like this eco game ? i saw a minecraft tutorial and know how a chunk and cube work but how to make this grass rounded cube ? someone know or have a forum or something ?
wallahi
It's hard to tell where exactly the grid edges are so it's hard to identify the bricks needed but I'd assume it's just couple premade 3d models for each piece type (inner corner, outer corner, straight edge, etc.) needed to construct any shape. The right meshes to construct the block could then be decided based on the surrounding blocks or lack thereof. if you have multiple 3d models for single piece (like straight edge), you can pick one by random, you just have to make sure the models match together seamlessly (connection points must be identical)
Is there a way to have "persistent" actions on an action map? such as moving and pausing which will be present in all action maps
no
i have different action maps for each mode, so in a boat, in a car, just normal walking around. but all of these will have a move action and a pause action that work the exact same way
maybe im doing something else wrong
So its not a mesh created in unity script you think ?
The typical approach is to put those things in a separate map that you always keep active
Can anyone explain me how to get rid of this?
I tried exporting the Unity Playground Character via Export -> Custom Package and Imported it the same way.. but idk what "already" is supposed to mean in that Error message.. like yeah.. its the only location where that's defined...!?
why does this not apply blur
Make sure you've followed the guide pinned in #๐ฅโpost-processing and using correct one for the pipeline you are using
k thank u
stil ain't working
Try asking more in #๐ฅโpost-processing
This is a code channel
okay
Would this be the right place to ask about sprite shape? I have one main sprite shape im updating every frame (growing vine) which seems fine for my pretty good dev computer but I suspect its the root cause of reports of performance issues on computers with lesser capabilities. Is there anything I can/should do to get a similar effect of a sprite shape growing over time without per-frame internal calls of BakeMesh frying some users' computers?
For starters, try profiling your project and seeing how much time the feature actually consumes.
yeah i cant really observe any spikes running on my good computer
I do see a solid amount of time in the sprite shape bake mesh but its like 2ms out of 4ms
i guess on another computer that might be like 30ms out of 60 though?
It's really unlikely that both values grow linearly depending on the machine performance.
Did you actually ask your users what hardware they have?
its definitely the single most expensive thing im doing but I suspect maybe its hitting memory limits or something else causing a significant slowdown?
nah these are just internet strangers from newgrounds
Okay. What exactly is that "mesh baking" is? Can you take a screenshot of the profiler data?
sure one sec ill try to find a good example frame. But basically, the official SpriteShape package checks if the spline input data has changed, and if it has, rebakes the geometry of the sprite shape
Does OnCollisionEnter require both objects to have a rigidbody?
so here's an example call stack where my sprite shape usage is using up a lot of the frame time (3.33/8.71)
Thank you
it might just be the case that this type of usage where its being dynamically updated every frame or almost every frame isnt intended/well-supported but I'm wondering if there are maybe some settings I can change or ways I can change my approach to make my usage of this package more efficient
Seeing how much time it takes, it must be quite a complex mesh, right? What does it look like?
How big is the spline?
it grows over time and probably ends on like a few dozen control points. I dont see much appreciable difference in cost as spline gets longer
ignore pink thats soemthing else
Hmm... That shouldn't take 3 Ms imho. Does the time change if you disable collider generation?
Can you expand the bakemesh further?
i only have update collision as an option in debug inspector, theres no collider on the spriteshape though. weirdly it seems slower with update collision disabled. It looks like it just is too many points maybe, it just turns into BezierPoint math im assuming, bezier expanded is just multiplication
In blender, I made an animation and there is an object, colliderObject, that represents the collider. Throughout the animation, the colliderObject, which represents the collider, changes size. In unity, I then attach a collider to this colliderObject, in hopes that when the animation runs, the collider changes size along with this colliderObject, but it doesn't. How do I go about fixing this issue?
Did you try reducing the details setting to lower quality?
I just plumbed that through to a UI so I'm gonna see if that makes any differnce on a low power laptop I got the back of a closet
Best thing to do is probably just profile on that machine that's actually reproducing the serious perf problems
If you have that option, that's the best
In response to that deleted message
You are using euler values in a quaternion, you shouldnt directly assign it. Use Quaternion.Euler
so i want my gun sound to play when i shoot and for some reason my code isnt working and idk what to do https://pastebin.com/UyU5xt06
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.
"isnt working" is as vague as it gets. have you debugged anything like if the code to play audio is actually running
you need to be more specific about what exactly isn't working. also if you're gonna use pastebin please at least have the courtesy of selecting the correct language so there's syntax highlighting instead of a giant blob of grey
i mean when i shoot everything works but the song doesnt play
well yes that much was clear. Start debugging to see if the line even runs
mb i just started using pastebin idk how to do all that. no errors
the only reason your sound wouldn't play is if either audioSource or gunshotSound is null or you have other errors in your console preventing that code from running. if you have absolutely no errors in the code then you have your answer
oh ok
also once you start shooting you just don't stop shooting until you are out of bullets? is that intentional?
yeah i have an ammo system
that was not what was in question
oh
you currently do not stop shooting until you run out of ammo no matter what because you continuously invoke the Shoot method from within the Shoot method as long as you have ammo left
i certanily do
yes, so if you do not want to keep shooting even after you have released your shoot button, you need to not invoke the Shoot method like that.
It could be but I think just storing the information about which pieces to draw and where (and draw them procedurally in shader) could be comparable in terms of performance. I think it depends on the amount of the map you need to draw at once and the sizes of the chunks (higher chunks for example means more expensive to generate) as well as the amount of rounded blocks compared to regular cubes whether generating the mesh would be worth trading generation time for faster render
What could be the reason for a crash right after the build is launched?
The error is ".../globalgamemanagers.assets' is corrupted! Remove it and launch unity again! [Position out of bounds!]
The build is DedicatedServer build, on Linux.
Unity version is 2023.2.20f1
This has been a problem for very long time now.. How to do these properly? Make a layoutgroup calculate it's content size and positioning properly?
private IEnumerator StartAnimation()
{
canvasGroup.alpha = 0;
// yield return null;
SetLayoutGroups(true); // enables layout groups
yield return null; // hoping the layout groups adjusts their size
SetLayoutGroups(false); // turn off layout groups
yield return null;```
Hi ! it might be weird but, i got a vector3 and i want to convert it as an unique int but it must be between 0 & 360. I'm struggling a bit to find a way to do this :/
ints? so you only have 360 possible outputs?
yep
vector3 is infinite tho
do you mind having 2 vec3 that returns same id?
cause it's impossible to not have overlaps
the real question is what is you gonna use it for 
What is a good unity extention for VSCODE
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
โข Visual Studio (Installed via Unity Hub)
โข Visual Studio (Installed manually)
โข VS Code
โข JetBrains Rider
โข Other/None
autocompletion is fine enuff to do things without stressing too much
I'm not allowed to say more so it's a bit complicated to explain aha
But okay thank's maybe i'm not heading in the right way then
Hi in ugui is there a simple way to sort child elements at runtime by name for draw order? Rather like a layout group but an order group?!
well, goodluck with that, I probably just missing something but the problem doesnt really makes sense in the surface ๐
Simply, what you're asking doesnt make sense and isnt possible. I doubt this problem came from some reputable company that made you sign an nda.
I guess this could even be related to the pigeonhole principle.
If you state the use case, itll be way easier to suggest what you should actually do
like a transform.SortChildren(predicate)?
private bool IsColliding(Vector3 targetPos)
{
Vector3 start = targetPos + Vector3.up * (_capsuleHeight / 2 - _capsuleRadius);
Vector3 end = targetPos + Vector3.down * (_capsuleHeight / 2 - _capsuleRadius);
RaycastHit[] hits = Physics.CapsuleCastAll(start, end, _capsuleRadius, targetPos - transform.position, 0.1f);
if(hits.Length != 0)
{
Debug.Log($"{hits.Length} : amount of hits registered");
foreach (RaycastHit hit in hits)
{
float angle = Vector3.Angle(hit.normal, Vector3.up);
Debug.Log($"{hit.collider.name} : name of hit, {hit.normal} : normal of hit, {angle} : angle of hit");
}
}
return false;
}
Hello again, I am trying to figure out how I can detect floors/slopes from walls dynamically with a CapsuleCastAll.
As I currently have layermasks in my prototype world that can differentiate for me what is a wall and what is a floor. But when I am going to make my world full of different models and heights, I don't want to lose time placing layermasks and collisionboxes everywhere.
In this current debug setup, I can can see all the collsions of my Cast but there is an issue:
Ground (which should have an angle of 0) says it has an angle of 90 with a hit.normal being Vector3(1.00, 0.00, 0.00) or Vector3(0.00, 0.00, -1.00) (based on walk direction).
Walls (which should have an angle of 90) says it also has an angle of 90 with the same hit.normal values.
Only slopes partially work, with them showing a hit.normal of Vector3(0.00, 0.80, -0.60) and an angle of 36.88[...]
What might I be missing?
Unfortunately i can't. But it's good to know that i'm not doing the right method, thank's !
Here is are some references
yes, I mean it is just a sort order. I can write one, but maybe somethign exists
Afaik there's none builtin
Still cant figure out
ok I will try sorting & using transform.SetSiblingIndex
Soooo dug a little deeper ... Sphere and Capsule casts just don't work like a regular RayCast would when hitting a point ...
That's stupid yet logical ... maybe?
I managed to make it work, but what would be the best route to take if I will be needing regular RayCasts when trying to detect walls?
Should I do 3 casts (foot, middle, head)?
I don't want my player to walk through walls still but don't want to overload someone computer with thousands of checks...
Assuming youโre looking for the angle of the vector uโd prolly need some vector projection onto the ground first before you calculate said angle and get that into an int
Obviously can only be approximated - to a terribly limited degree. If you are talking a normal vector then you can reduce it to the sum of 2 angles - actually that is not do-able either with 1 int! Forget it!
Just a note, even though you corrected yourself. Unique ID cant be obtained from summing 2 values ever. 0 + 1 and 1 + 0 give the same result yet are completely different vectors. This topic ties into hash collisions
The only way would be if the value was like bit shifted which doesnt apply here
no I know - you need to use bits of course
I am building the project for the web and enabling the Development Build option my project runs smoothly on Development Build so I keep it but there is a label at the bottom right corner. can I remove this label while keeping the Development Build option enable?
I'm reading some docs and is it okay to use string as ID for items? Like SODA, SHIELD...
It is better to use an enum in this case. Or create constants
I think the docs miss the actual reason why this is not adviced
The reason is "magic strings"
I did enums but it's getting worse
when i load scenes it breaks the entire game, why??? (it works perfectly fine if i just run that scene by itself)
Short answer, don't use them. Long answer, you can use them, but avoid magic strings by using things like constants, or store the keys in a way where there's not a change that you accidentally mistype them
Another reason is avoiding allocation of strings but honestly storing stuff in constants or persisting variables kind of omits this issue anyway
Can i use assets that are free on the unity store, and the sell my game?
Assets will have a license + optional requests when you use them. When you abide those it's fine
Also, this is a coding channel
where do i find those?
Well, I use them in a scriptable object Item which has a lot of information like level, name,... and ID is string.
Stop crossposting and use the proper channel. This is a coding channel
is that not the proper channel
If you don't have to write the string manually twice it's fine
The whole point is avoiding performance issues and magic strings
Is your issue related to code?
i believe it is
I understand magic strings but performance issues?
Then you should share the code. I doubt it is though
Seems more like visual issues
where else am i supposed to ask
Because strings must be allocated. If you do this often you allocate something that can be avoided
Usually a minor difference but it can add up
Numbers don't have this
If you don't know the channel then post it in #๐ปโunity-talk
Only thing I am doing with those strings is comparing them
Like case "SODA" do something
That's fine as long as you don't write it twice
Point is, if you happen to change the id of the thing to SODA2 for example, then the check will suddenly be SODA2 == SODA
Yeah, but that's the same for enums
If you store these things in constants, i.e. internal const string SODAKEY = "SODA", then the code just needs to use this constant when assigning the id, and comparing them
Same for enums, yes, but enums are limited to what is defined at compile time
Technically you can use different numbers, but it becomes unclear what it does and you might as well use constants then
Yes, I tried using numbers for ID but then later I didn't even know which item is which
Constants also fix that
Constants represent the id by text, and you can continue using numbers
My whole inventory system works on structs and saving them into dictionaries
I would honestly advice you use constant numbers
Strings are nice, but it's pointless to use these when numbers work
I was also thinking of a converter or something like that
Also FYI, basically all games use numbers. If you need to do comparisons, use them with constants, or implement proper comparisons on other things on the item. For example, Soda might also have a unique label to specify its name that you can check
If I want to use constants then I have to declare new constants to every new item?
I understand that now
Using constants is very smart
{
public const string SODA = "soda_01";
public const string SHIELD = "shield_01";
...
}```
You can also just define it in the item
public class Soda
{
public static int ItemId = 10;
}
Soda.ItemId == 10
You can also write a custom editor script and still have an option to use it in the editor
Also, idk how far Unity is in C# version but you might eb able to use this https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/tutorials/static-virtual-interface-members
Then you can write an implementation in an actual interface
I wonder, how is that done? It would be awesome
You can still use an interface, but it would not be static otherwise
Example:
public interface IItem
{
static abstract int ItemId { get; }
}
public class Soda : IItem
{
public static int ItemId => 10;
}
You just keep all constants in the list, and replace a string field with dropdown with these const values
Okay, thanks!
I think if you have an id field it means you don't set it up in the code. I think @hard tapir has it as a field in ScriptableObject
Yeah
yo guys is it easy to code a point and click game?
It is easier than MMORPG but it is still a challenge
yk i just care about the part of code that sais: if i click this thing anither picture appears yk?
i wanna make an escape room type of game nothing too serious
Every complete game is serious, but it is doable. If you want to make it you should absolutely try.
im trying to do something fun but a bit scary at the same time, im going for a 15 minute experience just for laughs with friends
[Photon Pun] I can't figure out how to set a variable from one Client to another.
I want to set "const Money = await api.setItem(projectId, playerId, {
key: "Money",
value: 0,
});" as protected not as default. How do I do this in unity cloud code js?
I'm trying to transfer the basic Unity character from the Playground into a existing Project of mine..
I selected all references to the player character, exported them as a custom package.. so far so good..
However when I import said package, some of the scripts prompt me with this weird error.. implying that its already there... any suggestions?
My Android app crashes randomly and in the logs I can see this error keep repeating many times:
[EGL] Failed to create window surface: "EGL_BAD_ALLOC": EGL failed to allocate resources for the requested operation.
What is this? Is this a memory leak issue?
I'm using Unity 2022.3.25 and I have plugins like AdMob with mediations, Firebase, Facebook etc.
This sounds like a graphics api issue. Never heard of EGL, but it seems to be related to Opengl
What OS are you using?
Thsi is happening in Android
Ah, okay then. What graphics API do you have enabled in the player settings?
apparently EGL means Embedded-System Graphics Library. I didn't know that either.
OpenGL
One possible cause is that you're just running out of memory
Wasn't there several versions of it?
Yes, when I googled it, people are saying that it's an out of memory issue.
Use the profiler or the dedicated profiling tools for your device to measure the memory consumption
OpenGL 2 and 3 is enabled in Unity Project Settings
ok, I'll try that. The issue is that this is a really random one and we cannot easily reproduce this.
Might need to use dedicated profiling tools then.
Do you recommend any tools for that?
Can somebody help me with this?
I'd start with unity profiler to see the memory consumption. Then something dedicated to your device. That would help with troubleshooting graphics API issues or GPU crashes.
Not familiar with what tools there are for Android, but there're some mentioned in this article:
https://unity.com/how-to/profiling-and-debugging-tools
ok, thanks for the help
It returns from that method, meaning the execution of that mwthod ONLY will end
//Drop if equipped, "Q" is pressed and fpsCam is playing the "Idle" animation
if (equipped && Input.GetKeyDown(KeyCode.Q)) Drop();
how Do I do This ??
I wanna call the drop function if the fpsCam is playing the Idle Animation
I have no idea what fpsCam is supposed to be so I doubt anybody can answer this question. Please share more context
It's the camera
Basically this is a pickup and drop script for my first person shooter guns
I don't want to allow my guns to be dropped when I am aiming down so I want my drop function to be called only when the camera is not zoomed in (Idle animation)
Make a bool, aimingDownSights
Use that for both starting and ending the animation, as well as allowing drop behaviour
I feel like I am going crazy, I am profiling some of my code and this method has a ton of String.memcpy() invocations. But I can't for the life of me figure out where they would be coming from. Any ideas? It is all pretty straight forward...
https://gdl.space/urapovugoh.cs
(For context, the method generates a bunch of mesh quads for UIToolkit, to denote milliseconds in a timeline UI)
well, it's a bunch of entries in the list, but each one is just a single invocation
Almost certainly the SetAllVertices etc
it looks like String.memcpy shows up when large structs are copied
it's not actually string-related
Ah - that may also make sense
That would be the most effective way to copy structs
But they should then be within the SetAllVertcies method, no?
Ahh both SetAllIndices and SetAllVertcies are doing a nativeSlice.CopyFrom() internally. I guess it would be that then?
Nope, that is it's own entries.
So... would it be the assignments of the structs to the arrays then...?