#archived-code-general
1 messages ยท Page 310 of 1
np
if I'm using dictionaries for tutorial dialogue (string, int) is it more efficient to have one large dictionary or multiple small dictionaries? or negligible differences
Key access is almost O(1) for dictionaries. So if that's all you'll be doing, that will be faster than deciding which dictionary to use and then getting the key
gotcha, thank you
Guys i dont actually know how to code so should i use visual scripting?
visual scripting is more of a tool, but you need to know how coding works to really start developing with it
well, depends. Usually the ones who are creating visual scripts are those who have some idea of coding, making it easier for other developers to work with
is there any instant suggestion on what to amend with my game? Raycasting works fine in the editor, however doesn't seem to be functioning correctly in my build (using mono, on Fedora Linux)
You could also just learn a new skill. Not sure why that isn't an option.
this has been bugging me a lot since it's a crucial element of my games tutorial
var rayOrigin = activeCinemachineBrain.gameObject.GetComponent<Camera>()
.ScreenPointToRay(Mouse.current.position.ReadValue());
if (!Physics.Raycast(rayOrigin, out var hit, maxInteractDistance)) return;
Debug.LogWarning("tag: " +hit.transform.tag);
Debug.LogWarning("object name:" +hit.transform.gameObject);
Debug.LogWarning("parent name:" +hit.transform.root.gameObject);
could draw some debug rays to be sure it's correctly going into that direction
I apologize if I already asked this, but how do I make clones do different things in unity?
they're all drawing correctly in editor, I'll test w/ the build now
Enemy enemy1 = Instantiate(EnemyPrefab);
Enemy enemy2 = Instantiate(EnemyPrefab);
enemy2.kill(); //enemy2 dies but enemy1 is still alive
nvm can't use debug.drawray in actual builds ๐ I'll report back with a linerenderer v quick
right, or generate a mesh at the point it hits, but it may not be hitting is the issue too
Would this also work if the size is the size of the orthographic camera? Because it seems you think the canvas/map is being scaled, while it's actually just the camera that's scaling
found out the reason - the build is defaulting to my 3rd person camera for some reason, hence the mismatch of raycast lineups ๐
I do not recommend it, no.
Fixed it, it was script execution order being a PITA.
Seeing as this didn't work, I might just figure out the percent increase of the deviation when the player scales and just correct the position manually with that percent increase when the player clicks XD Because this has been an issue for days, and it's getting OLDDDDD
Brute forcing is the only way I can think of solving this issue lol
Seeing as how when the player scales the camera up, the deviation of where the player clicks and where the destination was set grows, I can find that increase and offset the deviation
I haven't worked a ton with the orthographic camera, but if I remember how it works, it should still scale correctly.
Lol ok
Wouldnt you want to set it to the mouse position instead of "position?" (Honestly i have no idea how c# works, i just started with unity)
I wish it was that simple ๐
Sadly because my minimap is a lot bigger than the screen, I need to use a camera that feeds its frames to a raw image component that lets the player see the minimap. And since that's how the user is interacting with the minimap, through a UI image, instead of the minimap itself, I need to do calculations that I don't understand and are frustrating me, to figure out where exactly the player clicked on the minimap.
And as you can see. I am failing XD
In the video, I use the logic you mentioned, at least I hope I'm using it correctly XD And you can see that the positions that are set are not only incorrect, but also the distances are not consistent.
Lets say the player clicks on square A1, and the destination is set at B16 (because the position is incorrect). Now the player clicks on square A2, you'd expect the destination to move to B17, but now it's C20, or whatever.
That's why I'm just beginning to give up and want to brute force this stupidity XD Because at least, even with the camera's scale deviating the offset, it's consistent.
From the video is looks like an overlay which would make everything so much easier if it were, so if you can't figure it out with world and a ortho camera try devising something up using that instead.
Still, I've not really had any issues with a ortho/world cam like this
An overlay? What do you mean.
In the past I tried using just a simple scroll rect with the map inside the scroll rect, and whatever is outside of the viewport is masked. But I ran into a major problem with centering on objects within the map, like the players ship
because you can just use screen coordinates and then translate it to local coordinates on the map
I dont believe you even need to set a camera for localpointinrectangle if you're using overlay I think
I had some examples from before, but I'm feeling like you should try something easier first and see if you can do it that way
and ditch the scaling stuff for now
I'm still not sure what you mean by an overlay.
Do you just mean putting the map into my 2D CanvasGroup and using a mask to make the viewport smaller?
Give the minimap a canvas that supports overlay. Make the pivot on the minimap similar to the world map (perferably something like the bottom left so you can only have positive values that dont pass through the origin).
if the max x and y values are say 40x and 40y locally, add that to the pivot of where your mini map is and you would have the world location from the minimap
or however you're keeping track of the minimap's world pivot
Am I just stupid? XD
I understand what you mean by the pivot and positions, but I can't figure out how to give my minimap a canvas overlay. I switched the minimaps canvas from worldspace to Screen Space Overlay, but that does not seem to be the intent because now it just covers the whole screen lol. Even when I switch the sort order
Only the phone mini map should be the user's screen right? It will always render on top, but you can always hide/disable it
sort order will only affect other overlay canvas
{
float[,] treeNoise = Noise.GenerateTrees(size, size, 0.5f);
float worldX = 0;
float worldZ = 0;
Matrix4x4[] matrices = new Matrix4x4[size*size];
Vector3 meshPosition = mesh.transform.position;
for (int y = 0; y < size; y++)
{
for (int x = 0; x < size; x++)
{
float rngGrass = UnityEngine.Random.Range(0f, 0.5f);
worldX = meshPosition.x + x;
worldZ = meshPosition.z + y;
if (treeNoise[x, y] < rngGrass)
{
Vector3 positionGrass = new Vector3(x, heightMap[x, y], y);
matrices[x + 10 * y] = Matrix4x4.TRS(positionGrass, Quaternion.identity, new Vector3(1, 1, 1));
//GameObject grass = Instantiate(grassPrefab, new Vector3(worldX, heightMap[x, y], worldZ), Quaternion.identity);
//grass.transform.parent = grassChunk.transform;
}
}
}
Graphics.DrawMeshInstanced(grassPrefab.GetComponent<MeshFilter>().sharedMesh, 0, grassPrefab.GetComponent<MeshRenderer>().sharedMaterial, matrices);
}
Im trying to instance many many instances of the grass procedurally using the DrawMeshInstanced bc I read that it helps make stuff not as laggy. Here is my grassPrefab.
however I get mesh is null error and stuff and dont really know how to fix it
I don't understand anymore. I think I'm just stupid at this point.
I figured out how to put my minimap graphics behind the base UI, the buttons, panels, etc. But my problem rn is that the top of the panel shows the minimap canvas, when that should be showing my 3D water. No clue how to fix that. And also I can't change the canvas's anchor/pivot. I'm guessing I need to make make an empty parent that is 10,000x10,000 which is anchored to the bottom left that holds the entirity of my minimap graphics.
one of my switch statements isn't calling break when the conditions are met, extremely weird.
case { x: 0, y: > 0 }:
if (!TutorialController.IntroComplete() && TutorialController.nextKeyToPress != TutorialController.NextKeyPress.Forward) break;
TutorialController.TutorialChecks["Forward"] = true;
break;
the value is not being updated anywhere else in my script
seems to be working for the remainder of my switch statements, which is practically identical
switch (movementInput)
{
case { x: 0, y: > 0 }:
if (!TutorialController.IntroComplete() && TutorialController.nextKeyToPress != TutorialController.NextKeyPress.Forward) break;
TutorialController.TutorialChecks["Forward"] = true;
break;
case { x: 0, y: < 0 }:
if (!TutorialController.IntroComplete() && TutorialController.nextKeyToPress != TutorialController.NextKeyPress.Backwards) break;
TutorialController.TutorialChecks["Backwards"] = true;
break;
case { x: > 0, y: 0}:
if (!TutorialController.IntroComplete() && TutorialController.nextKeyToPress != TutorialController.NextKeyPress.Right) break;
TutorialController.TutorialChecks["Right"] = true;
break;
case { x: < 0, y: 0}:
if (!TutorialController.IntroComplete() && TutorialController.nextKeyToPress != TutorialController.NextKeyPress.Left) break;
TutorialController.TutorialChecks["Left"] = true;
break;
}
any suggestions?
Debug. Add logs or step through the code with the debugger to see what's happening when the issue occurs.
the breakpoint at the condition states that the break in the switch statement reaches the conditions to do so though, that's the thing
there is nowhere else in my project updating these values
Wdym? It reaches the conditions but what? If it reaches the co editions and doesn't break, then the conditions are returning false.๐คทโโ๏ธ
You should be able to see what values are returned in the debugger.
I feel like I don't understand what the actual issue is...
!TutorialController.IntroComplete() && TutorialController.nextKeyToPress != TutorialController.NextKeyPress.Forward)
this.. IntroComplete returns false, nextkeytoPress equals to forward, but the && should mean that it needs to be both conditions
its meant to be breaking out of the switch statement before reaching TutorialController.TutorialChecks["Forward"] = true; but it somehow still reaches this
Then one of those are not what you think.
exact same conditions are working with the remainder of the switch statement.
I mean, the values are not what you think.
Try grouping the conditions in brackets. It could be that the order of operations is not what you think it is
Specifically, wrap the comparison expression in brackets
TutorialController.IntroComplete()
will be false. according to debugger anyways.
TutorialController.nextKeyToPress != TutorialController.NextKeyPress.Forward
This will actually be true tbh so that's only one condition met
still no change
Not sure where that dictionary comes from. And the last screenshot doesn't specifically show if the condition is true or false.
Share the IntroComplete code
public bool IntroComplete()
{
return TutorialChecks["IntroductionComplete"];
}
dictionary is created in start:
TutorialChecks = new Dictionary<string, bool>
{
{ "IntroductionComplete", false},
{ "Forward", false },
{ "Backwards", false },
{ "Left", false },
{ "Right", false },
{ "Jump", false }
};
Using strings as a key is kind of unreliable. But I don't see any typo.๐ค
private IEnumerator InputPrompts()
{
// kill me
ImageTweening.ClearTextAlpha(ref tutorialTextHint, false);
yield return new WaitForSeconds(2f);
tutorialTextHint.text = InputPromptTexts[0];
promptW.SetActive(true);
ImageTweening.AlphaPrompt(ref tutorialTextHint, ref keyPressW, ref keyPressWalt, true);
TutorialChecks["IntroductionComplete"] = true;
yield return new WaitUntil(() => TutorialChecks["Forward"]);
this is the point where Introduction complete is set to true, and then waits until forward - but it seems to be listening for this before those text prompts and the yield return new WaitUnitl() seems to happen
Set the value in the IntroComplete to a local variable so that you can see the value retrieved from the dict during debugging
two secs
Same in your switch case. Set each of the conditions to a local variable and see if they have the expected value.
goofy ass
yeah, this is really odd
looks like both the conditions to break are met, it just doesn't break
? it's working as intended
Yeah, the second condition is false
apologies for the waste of time lmao
dev sprints are frying my mind rn
well, even with the ! removed its still not breaking :p
that expression is still false
false&&dont care =false
realised I need to set the != to ==
that would still make no sense. It looks a lot like you're pressing the forward button on the forward prompt, and then are shocked that the forward button tutorial is being set as complete
got it working 
if (!TutorialController.IntroComplete() && TutorialController.nextKeyToPress == TutorialController.NextKeyPress.Forward) break;
this was the statement that I needed
I don't think so, might want to check again. Does x: 0, y > 0 represent moving forward?
yeah, read as a v2 from unitys input system
Finally working as intended though
If it is, TutorialController.NextKeyPress has been designed terribly. Atm you can only complete the forward tutorial if you moved forward and the next expected keypress is NOT forward
nopers, it prevents different keys being shown when the intro text is still being shown on the screen.
๐คทโโ๏ธ if you're happy with it, great. But principle of least astonishment applies here, and my read is that TutorialController.NextKeyPress expression is so that you don't trip the other tutorials until prompted. Apparently it does not, so I would rename it at a minimum
public enum NextKeyPress
{
Forward,
Backwards,
Left,
Right,
Jump,
Complete
}
by default the enum will have forward as its default option - I'm assuming what you're implying is to add an entry in the enum beforehand so Forward isn't the first / default entry?
switch (movementInput)
{
case { x: 0, y: > 0 }:
if (!TutorialController.IntroComplete() && TutorialController.nextKeyToPress == TutorialController.NextKeyPress.Forward) break;
TutorialController.TutorialChecks["Forward"] = true;
break;
case { x: 0, y: < 0 }:
if (!TutorialController.IntroComplete() && TutorialController.nextKeyToPress != TutorialController.NextKeyPress.Backwards) break;
TutorialController.TutorialChecks["Backwards"] = true;
break;
case { x: > 0, y: 0}:
if (!TutorialController.IntroComplete() && TutorialController.nextKeyToPress != TutorialController.NextKeyPress.Right) break;
TutorialController.TutorialChecks["Right"] = true;
break;
case { x: < 0, y: 0}:
if (!TutorialController.IntroComplete() && TutorialController.nextKeyToPress != TutorialController.NextKeyPress.Left) break;
TutorialController.TutorialChecks["Left"] = true;
break;
}
seeing as movement input is built like this, it stands out a tad since it's not consistent
no, I'm saying your NextKeyPress makes no logic sense as-is. If I have a tutorial controller that prompts "Press W to move forward" and it had a NextKeyPress property, my expectation is that NextKeyPress is W. But your logic will only mark the forward tutorial as complete if NextKeyPress is literally anything but W
ah, the script will only update / register the W keypress once the "intro" is complete. the intro is the sequence of text to be shown before the input tutorial. probably my goofy ass naming schemas being confusing-
so its basically waiting for the introduction to be complete - and since by default the enum of nextKeyToPress will be forward, if those two conditions are true then it'll break out
but if the Introdution is complete, and the key is W - then it'll update the value and confirm that Forward / W has been pressed
@naive swallow
I found when it happens
If I change any script while playing the error occurs
even if I just add a comment
ping me back when you have some spare time
Hello all. Is there a way to make unity compile scripts faster? My unity just recently started taking ages to compile scripts for even the slightest changes in my code, and I have to wait twice the time coz I'm using ParrelSync. Any help?
I've also tried the fast script from the package manager but I didn't notice any change
If it started taking ages suddenly, it must be some sort of bug or something. You should look investigate the domain reload and compilation via the log or even try to profile it to find the cause of the issue.
Okay, thanks. Im going to try that
suggestion: Don't implement tutorial for basic WASD walking and separate checks, that's a missed game design decision ๐
wdym?
I mean many game design materials tell that people generally don't like, don't play and skip tutorials. That implicit unlock conditions are often annoying (e.g. having to click all of WASD to complete a movement step) is often annoying and that people generally opt out of tutorials if the game controls and control scheme is "universal", i.e. WASD + Space etc
ohh I get that
it's just part of my submission criteria unfortunately ๐
since its a uni project
and often just a simple box with "< PREV | NEXT >" with information displayed is bettern than "milestones"
ah yes, if it's uni project then that's unfortunate
I'll add an option to skip the basic controls either way
thanks for the input though, it is appreciated
!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.
I just stumbled into the weirdes issue I've encoutered ever working in Unity. An object is literarily losing its reference and getting it again during a single frame. https://gdl.space/utatapajow.cs
Note: This happens if the scene is reloaded. Not otherwise. The objects/scripts themselves are not set to "DoNotDestroyOnLoad". Ever scene reload should reset everything from start. Thats the intention anyway.
Anyone have an idea what is going on here?
That piece of code doesn't confirm in happens in a single frame. Try logging Time.frameCount in both methods and look at the two most recent logs before the error occurs
THat is true. GIve me a sec
Updated code and log confirms @simple egret :
https://gdl.space/mefaqubahu.cs
How is this even remotely possible. I'm not manipulating the object otherwise.
Yes, it happens in one of those frames. Except I'm not manipulating the object elsewhere.
Its being called on a state change
hm you got me on to something now
Nope that was not it
@simple egret its being called on an event. I've checked and the event is fired exactly once
Seeing it only happens after the scene is reloaded it must be something happening there?
When you execute SceneManager.LoadScene() it doesn't happen right away, so if you have code like this:
Debug.Log("a");
SceneManager.LoadScene("bla bla");
Debug.Log("b");
The scene will not be loaded when the second debug log is executed. Scene loads happens at the end of frame
If you need to execute code as soon as the scene is loaded, subscribe to SceneManager.sceneLoaded event and put your code in there
This code is is executed way past scene loaded finished though
Or use a coroutine to check for the scene being loaded
private IEnumerator LoadScene(string name)
{
SceneManager.LoadScene(name);
yield return new WaitUntil(() => SceneManager.GetActiveScene().name == name);
}
it is loaded and interactible. Only when the user is trying to press the screen this happens. And it only happens if the scene has been reloaded. Not on first run.
Then your object is just getting destroyed by something else. If you have a script on that object, implement OnDestroy() and put a log in it to see on which frame it gets destroyed
With the right settings a Particle System can destroy the object it's on when it finished emitting, so check that too if you have a PS on the vanishing object
"Stop Action" field set to "Destroy"
share the rest of the code.
OnDestroy is only called when scene reloads. Upon/after OnSceneLoaded the object holding screenObject is not being destroyed. I can clearly see it in inspector, the screenObject is in fact showing the current screen. For whatever reason the reference is just gone that split frame.
Well if that object is being destroyed, but the script that holds a reference to it is not (it has DontDestroyOnLoad) then of course it'll lose the reference, and you'll have to find it back
Both objects need to be DDOL for references between them to be kept
None of the scripts has DDOL. They are destroyed and supposed to be recreated from scratch onsceneload. Breakpoints show they indeed are there onenable once the scene has reloaded. As the log shows, it is there. Then its not. Then its there.
The scene should be fully reloaded. No states are saved.
Yes that breaks scripts. Don't do that.
@simple egret the only thing I can think of is that the call to reload the scene is done in a Thread(). In there I call UnityMainThreadDispatcher to change scene (which works fine). Either way, object is there, not destroyed -> MissingReferenceException -> fine again.
The thread in question is a simple HttpListener (and a Singleton) but holds no references to anything except the SceneController.
I find it particularly interesting that the inspector shows the object all the time.
is it bad practice to represent an initially unknown value in a float by initializing that float to float.NaN?
Not at all, especially when you have the float.IsNaN(f) method to check for it
Do note that float.NaN != float.NaN!!!
So don't check whether it's NaN with equality operators
I'm at at total loss here
Hey guys,
Is it possible to have lfs and yamlmerge together on .unity ?
dont think so, lfs doesnt diff, it just checks hash afaik
If I have bigger than 100MB scene what should I do about that ? I should forget using yamlmerge on that ?
the only downside is more stress on git, if youre ok with it then its fine
LOL not even using SceneManager to reload directly makes a difference. This has to be a Unity bug with loading scenes.
More stress on git because of not using yamlmerge ?
no because it has to diff larger files
yamlmerge only helps in automating merge for unity yaml, afaik
git still will diff the files
Thanks
Howdy folks. How concerned should I be with garbage collection of orphaned stack-based objects? My target is mobile, so I'm attempting to be sensitive of garbage collection out of the gate, but am unsure if this will actually prove problematic in the long run. For example, I have numerous functions that instantiate new vectors to aid with computation for placement on a 2D grid. In one frame tick I might evaluate a 64x64 tile grid and so 4096 times a function will have declare a Vector2Int offset = new Vector2Int(someTile.x + propOffset, someTile.y + propOffset); and then use it in a calculation. I am guessing that all those objects will at some point get recycled? Or is the compiler smart enough to persist that memory forever due to its repeated use, thus eliminating the need for GC?
Hmm.. Try also printing if it's null in this line Debug.Log(screenObject.name); that you have in update
Or before it
vectors do not get garbage collected
Oh, good to know.
unelss they're fields on a class
Vector2Int is a value type (struct)
it doesn't get allocated on the heap
My Lists incur a rather hefty GC penalty when using Linq I've noticed. So I've been trying to be more judicious on those. Particularly with the results of circle casts and whatnot.
yes Linq is a GC trap
avoid it for performance critical pieces
use regular for loops
the stack pointer will decrement automatically to get back all data in "previous" function after you leave the function, this is how the stack memory is being freed
I appreciate the insight.
is it possible to inherit from something other than monobehaviour if I just want to attach some data to object without behaviour?
I tried Component/Behaviour directly but they don't seem to work for non-built in components
MonoBehaviour is the way to create scripts that you can attach to GameObject
If you want to attach your script to a GameObject, it must be a MonoBehaviour
yeah I just thought it's overkill since I don't want any methods
I don't see what the problem with that is.
I just want pure data
Then don't add any methods to it
that'd still make it check for existence of the methods, wouldn't it?
when calling updates/etc.
Sounds like you're engaging in some kind of speculative premature optimization
don't waste your time
so that information is cached?
It is not going to check if there is an update method every frame on every object
if that's what you're asking
if Update is not present in class, then its not calling the C++ engine method for example
if its present but blank, it does call it
alright
You have a few options, you could just create a Monobehaviour and not use the methods (this makes things easier rather than fighting against Unity's architecture but you have some overhead). You could also create a POCO (Plain Old C# Object) and have your the bulk of your system in their and call it from Monobehaviour (So the Monobehaviour becomes more of a wrapper/entry point allowing you to attach the code to a game object/entity). You could also do the same thing with a ScriptableObjects and use ScriptableObject to write the core of your system and then call it from a Monobehaviour when you want to attach it to a game object. I personally prefer the second and third options as not everything needs to extend Monobehaviour but you need them if you want to attach logic to components
does anyone know what could be causing this to happen? The cube only goes trough the wall at a specific angle and only in this part and i have no idea why that is, i really dont understand
as you can see here in the second video if i do this in a different part it doesnt go through
its only at that metalic part that it does and it doesnt make sense because they both have a collider
depends how ur moving the held object
the pre made collider of pro builder blocks
the way im moving the collider is by parenting the held object to an object called holdarea
heldObjRB.transform.parent = holdArea;
like this
You would have to explain how you're moving the object (and show code)
Also what do you mean by this? Are they both Rigidbodies? Dynamic? Kinematic? What does the hierarchy end up looking like?
This is the code
holdarea does not have a rigidbody
only the heldobj
Ok the parenting isn't really doing anything here
except maybe breaking things
It's your heldObjRB.AddForce(moveDirection * pickupForce); that is doing the moving
no the parenting does kinda move the object, it makes it so it stays more in place, i can show the difference between having it parented and not having it parented
yeah but you don't want that
moving it via parenting is very bad
any movement from that will ignore physics entirely
you want to only move your Rigidbodies via the physics engine
hum yeah thats a problem
or you get things going through walls
but i really dont like the way the movement is being applyed without it
def switch it to .velocity
Yes, set velocity directly
heldObjRB.velocity = moveDirection * pickupForce;
you can do it like:
void FixedUpdate() {
Vector3 diff = holdArea.position - heldRb.position;
heldRb.velocity = diff / Time.fixedDeltaTime;
}```
Then it will always move exactly to the desired position each physics frame
on my pickup script the only thing parented to player is the "HoldZone" which just track the ideal position which rigidbody should reach
like this?
ill try that thanks
this is similar to a solution i had tried one time
the only problem i have with it is it makes the object like shake a bit but is certainly
is interpolation enabled on your Rigidbody?
wow thats horrid
no
turn on interpolation
alright
oh yeah it looks a bit better
still shakes a little but it certainly isnt as bad
I use this method, not sure if its worse or better but its been good for me . I could be doing something wrong though ๐
private void FixedUpdate()
{
if (currentObj)
{
Vector3 targetDir = pickupTarget.position - currentObj.position;
float dirMagnetude = targetDir.magnitude;
currentObj.velocity = amount * dirMagnetude * targetDir;
}
}```
How does your player motion work?
What is amount and doesn't dirMagnetude * targetDir just give you velocity squared?
You're multiplying the diff vector by its own magnitude
which squares the length
yeah just realized, I wrote this 2 years ago so it sucks
if amount is 50 then it's equivalent to dividing by Time.fixedDeltaTime
yeah that is a bit harder for me to explain xD, the motion script im using is like a
copying the source movement
made by a guy on github
amount was 12
should be a pretty simple answer - is it CharacterController in Update? Rigidbody motion in FixedUpdate?
backwards for me also doesnt look bad but its just because the movement is slower going backwards
yeah must be the character controller being moved in Update maybe
while box is moving in fixed
yeah that's the reason - basically mismatch in cadence of motion
that's the problem with Update based movement in a physics game
and yeah in yours it is also going off the holdarea in backwards, but you dont notice it as much since it isnt going towards you
yeah just intentionally wanted to have a "slack" and not like "glued" to the hold pos. Plus my char collider isnt enabled to collide with box
gotta take ur wins where you can ๐ฆ
maybe i should just make my own movement script but after my attempt at making this holdObject script im kinda terrified of that idea xD
dynamic rigidbody based controllers are a pain
what could I do here to make it so if the value of diff is too high it sets it to a certain max amount?
because a problem im having now is that if im putting the block against the wall it eventually just flies off
or goes thought the wall
diff = Mathf.Min(diff, maxDiff);
thank you
It is what I'm doing. It becomes null mid-frame to my understanding. I have even gotten rid of any Singletons just to make sure nothing is holding it. This just HAS to be an engine bug. I see no other logic.
Can you show more of the error, like what line is actually throwing the error?
And what script.
You're assigning velocity the value of your direction. Normally you'd normalize the direction and use some scalar speed.
Else you'd want to limit the magnitude of the vector https://docs.unity3d.com/ScriptReference/Vector3.ClampMagnitude.html
Where can I read on some available solutions to implement gameplay modifiers? For instance, if I have a health component with int health value in it, and I want to make status effect that temporarily increases player's health, and another that cuts health in half, what are the common solutions to make system that could add modifiers to that int variable in the game?
I do suppose it would be saner to leave the original variable value untouched and only include modificators when you try to access it, rather than the modificators directly changing the value on being added\removed, right?
Hey, my json is still empty after saving, what am I doing wrong?
void SavePouchesToJson(List<(Vector3 localPosition, Quaternion localRotation, FFSPlateCarrierPouch.PouchType type)> pouchInfoList)
{
// Serialize pouch info list to JSON format
string json = JsonUtility.ToJson(pouchInfoList);
Debug.Log("Serialized JSON: " + json);
// Define the file path
string filePath = Application.persistentDataPath + "/pouches.json";
// Write JSON data to the file
File.WriteAllText(filePath, json);
// Debug log saved pouches to file
Debug.Log("Saved pouches to file: " + filePath);
}
is it running?
well for starters, JsonUtility doesn't like an array or list as the root object when serializing like that. and also i'm not even sure if it can serialize tuples
Yes of course, I even get the debug saying "Serialized JSON: {}"
oh yeah just noticed that
I doubt you can serialize tuples since you can't on the editor in the first place
make it a struct
if the buff affects "base status", i would prefer store them separately e.g. add 2 hp in 5s, 4 hp in 10s, 8hp in 15s, and you can have a priority to consume the additional hp that going to be timed out first, so when getting damage, you first consume from the 2hp.
for the others buffs that are plugged into some formula of calculating speed/attack etc, just store timer and "effect"
What I like to do is treat my original values as modifiers too, but as a flat modifier. Beyond flat I also have % increase and some other basic value modifiers, but technically everytime I get a new modifier I do a full recalc with all modifiers and keep track as to what had applied them so when I remove them I know for sure it won't remove my base modifier. Current Health/Current Mana and anything that seems like a resource would not be affected by modifiers, only variables which have a max, so stuff like MaxHealth.
Hi I am making a horror game and each room is a scene I have code that saves the scene name to a json file and that works fine on my menu I have a button to load the game how do I get the data from the json to load the scene name?
deserialize the json and read it
I'm not sure how
however - between scenes it shouldn't get to that point
json is only for saving to and reading from a saved game file
between scenes the data should just live in an object in memory
the code I tried to make is this: public void LoadLastScene()
{
string jsonFilePath = Application.dataPath + "/sceneName.json";
// Check if the file exists
if (System.IO.File.Exists(jsonFilePath))
{
// Read JSON file
string jsonData = System.IO.File.ReadAllText(jsonFilePath);
Debug.Log("JSON data: " + jsonData); // Log JSON data
try
{
// Parse JSON data
SceneData sceneData = JsonUtility.FromJson<SceneData>(jsonData);
Debug.Log("Scene name from JSON: " + sceneData.sceneName); // Log scene name
// Access scene name
string sceneName = sceneData.sceneName;
// Load scene
SceneManager.LoadScene(sceneName);
}
catch (System.Exception e)
{
Debug.LogError("Error loading scene from JSON: " + e.Message);
}
}
else
{
Debug.LogWarning("sceneName.json not found. No scene will be loaded.");
}
}
[System.Serializable]
public class SceneData
{
public string sceneName;
}
but it won't load the scene even though the name is in the json file
Yo ! I have a question, sometimes I want to add null check or some debug messages into my code but I don't because it will only be useful during development time and not into the final build. I heard this wasn't a good idea and I saw something that could be useful. Is using conditional compilation a good idea for these type of stuff, so that there are only compiled while developing and not in the final build ? For example this (this is a really simple example, but the idea is the same) :
#if UNITY_EDITOR
if (something == null)
{
Debug.Log("blabla");
}
#endif
what are your logs saying?
well there's your problem
but it does this is what is says in it: {"sceneName":"Hallway2 Office Exit"}
it gets compiled out
so what's inside the file is irrelevant
oh ok
your path string is incorrect
it's in appdata locallow
I don't understand
which is not Appication.dataPath
so how do I get it to read and then load the scene?
oh right
conditional compilation, it's a condition for the compiler
what path is it then?
I added something in my message, I forgot to precise that I don't want this code in the final build but only when i'm developing
System.IO has lots of classes/methods for you to check these things
Yes, what do you mean by this ?
ok thank you
you wrote the file so you should know where to
Application.dataPath is never the right path for this
Application.persistentDataPath is the correct path for save files
and if i add that it should work
using preprocessor directives (the #if you written) to differentiate different build target is common.
it will work when you use the correct path
we don't know what that is
only you do
I know how it works, but I want to know if using this in the cases I wrote is useful ^^
Or if it is overkill
you usually don't want debug.log in your builds, so what you're doing is technically the correct way assuming you dont want to clean up your project between builds
or any error checking in general (usually project settings can remove it all for you too)
Oh ok, I didn't know about this. So in theory this is the right way to go if I don't want to clean it myself ?
right, the compiler will know to remove it when you build for your platform
also useful for when you are building multiple different platforms because sometimes you'll need different methods of serialization
Yes I saw about this, this is cool
I will learn about the project settings like you said, and I'll probably use conditional compilation, thanks for the infos !
This makes no sense
is there an efficient way to do like filtered gravity? Like I want to be able to make the player a target of minor gravity for certain collectibles. I dont want to do a distance calc for every collectible and doing a circle cast every frame also seems maybe too wasteful? I can think of a couple ways to impl but wondering if someone has recommendation on good way
would it be preferable to set up the math such that everything is pulled but the magnitude of the pull is negligible beyond a certain distance?
it seems like im gonna need a distance value regardless if its gonna act like real gravity but maybe some estimation would be good enough and much cheaper
You don't need to cast if you just use a trigger collider. Add the results to a list on enter and remove them on exit. Check the sqr magnitude instead of the distance, then square whatever the other side of the comparison is
sounds good, thanks
Im trying to use sprite stacking in unity. As of right now i have the parts attached to a game object which is a child of the main object, the car. From what i know the only way to get that 3d rotation is by rotating each part as opposed to the game object. I have difficulties here, since the car(main object) rotates and changes its z rotation value. Am i supposed to counteract the rotation for the parts and somehow rotate them locally? Been trying to figure this out for a bit too long.
{
float[,] treeNoise = Noise.GenerateTrees(size, size, 0.5f);
float worldX = 0;
float worldZ = 0;
Vector3 meshPosition = mesh.transform.position;
for (int y = 0; y < size; y++)
{
for (int x = 0; x < size; x++)
{
float rngGrass = UnityEngine.Random.Range(0f, 0.5f);
worldX = meshPosition.x + x;
worldZ = meshPosition.z + y;
if (treeNoise[x, y] < rngGrass)
{
GameObject grass = Instantiate(grassPrefab, new Vector3(worldX, heightMap[x, y], worldZ), Quaternion.identity);
grass.transform.parent = grassChunk.transform;
}
}
}
}```
how do i instantiate the grasses more efficiently ๐ญ
rn the prefab is just three planes intersecting
with a shadergraph
Why does it need to be instantiated?
Why do you need to spawn it? Is it for procedural generation at runtime?
yeah
And I guess you're not using the unity terrain?
idk how to use it with my terrain mesh
Okay. Then the answer is there's: no other way to instantiate it.
Is it causing a performance issue?
a lot
During instantiation?
my gpu is running at like 60 ms or sum
like forever
GPU isn't related to instantiation.
and im p sure im not instantiating grass for the same chunk every frame
It's rendering that's the issue.
Before I proceed, did you actually profile and confirm that it's a GPU bottleneck?
That doesn't confirm anything. What is taking the CPU time in the hierarchy view?
You'd need to go over the profiler manual and learn how to work with it, but since I'm in a good mood:
- select a frame of interest by clicking in the CPU graph.
- your profiler is already in a hierarchy mode, so it should show data right away in the bottom part of the window.
- sort by "Time" and expand the topmost category as long as the element type has a big enough value(>1)
From what I can see, it looks like the editor loop is taking a lot, so perhaps there's no real issue here.
And you completely ignored the last step
Well, half of it
But yeah, it looks like editor loop is the problem here. Just to confirm: are you recording it during play mode?
p sure?
wait uh
Since most of it is being the editor loop, this test is not very reliable.
Can you take a screenshot of the whole editor window?
I've been working on an implementation of the a* pathfinding algorithm, and it's been working as expected for the most part. I've configured it to avoid being near walls by putting negative weights near them, and positive weights in the center of the room. This works fine, but with anything bigger than a 1x1x1 cube, it starts running into issues with clipping, especially with dynamic objects (eg. doors). I've added a rigidbody to the mesh so that it should push itself away from objects it comes in contact with, but I think because of the forces that move it, it still clips through. Is there an approach I could take to avoid having the collisions happening in the first place or some other way of avoiding this behavior.
Okay, now expand the player loop as I explained in the last step.
Can you stop switching between the GPU and CPU modules? I mentioned that you want to look at the CPU graph first.
Expand more
Do you have another camera in the scene?
Well, it definitely renders another camera, so there probably is
could that possibly be the reason
i think the grass model i imported from blender might have it
Why won't you expand in order? There's "context submit" that has higher CPU time and you skipped it?
Well, check the prefab and see if it has it.
Or just pause the game and search in the scene hierarchy
ok it does have it but i set it to false
like a while back
like unactive
It doesnt i just imported it from blender and forgot to delete the camera there
It could or could not be related to the camera in the profiler, but it would definitely make it harder to look for the actual culprit.
One thing before optimizing your game: make sure your assets are standardized and optimized, and don't have issues like unneeded objects.
alr i dleeted it but its still p laggy so idk if that was it
unity, typically, is single-threaded right?
Not sure what you mean by "typically," but most Unity APIs can only be run on the main thread so most code are written single threaded sure. You can write multi threaded code in Unity though and lots of games make use of that.
This could potentially indicate a GPU bottleneck.
It seems to be waiting for the render jobs to complete. You'll need to look at the other threads that it's waiting for.
typically as in if you don't call/run multi-threaded code as a developer
point is, is this code safe if I'm not as a developer implementing multi-threading (at this time)
public sealed class Singleton
{
private static Singleton instance = null;
private Singleton()
{
}
public static Singleton Instance
{
get
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}```
If you are accessing the singleton instance on multiple threads then yeah that can potentially get into issues like race conditions, but that's not limited to this piece of code in particular. Anything that can be mutated by multiple threads have potentials for causing hard to debug issues like race conditions.
yeah
but if I'm not running multiple threads, just using the unity API from a fairly intermediate level it should be fine right?
Sure.
Btw you can improve your code a bit by doing:
public static Singleton Instance => instance ??= new Singleton();
that's going to need explaining
valid, I'll be on my way XD
I'm having issues were my character won't jump. I'm following a tutorial but I don't know what is wrong.
https://paste.ofcode.org/?edit=a98Uh7PdStv65UasxT257W
might be dumb but how do i do that
ok I kinda knew the second but the first blew my mind
I got it to work, I forgot to add it to the start function
new issue, why does it stager when i look around? ๐ค
show the look around code?
https://paste.ofcode.org/?edit=g4pnvBe4LhpFQM29U2mvY, it's in there
what are you looking around with? mouse? keyboard? @oak panther
Mouse
My game has a Calendar that stores CalendarEvents in a sorted list to execute them as appropriate as time progresses. CalendarEvent holds an Action to call a function when the event is executed. I need the function of the Action to use a variable set of parameters. For example, in some instances, I need the calendar event to be able to call a function of signature Function(), in others, a function of signature Function(float), and so on. I'm looking for the cleanest and least annoying approach. Some possible solutions:
- CalendarEvent stores
Action<EventParams>, withEventParamsbeing a base class to something that I downcast. in each appropriate function. Downside: runtime, rather than compile-time type checking. - CalendarEvent is itself a base class that stores an Action<T> where T is defined based on a generic parameter of the derived type. Downside: annoying to define so many classes.
- Pass a lambda with no parameters in to the CalendarEvent constructor to define the Action and rely on closures to define the parameter type. So, e.g., CalendarEvents.action = () => {TypeINeed.dosomething();}. Downside: can't access the closed-over variable once the action is set. Closures have funky behavior.
- Define no-parameter functions that access whatever state is necessary and put those into the
Action. Downside: possible spaghetti code.
Any other approaches that are better than those above? If not, which is the best approach? Thanks!
I might be mistaken, but I don't see mouse input in that code
please show me where if it's in there?
It takes mousex and mousey. It uses the vector 3 method
yeah i dont see anything mouse related in here
please check?
public class PlayerCamera : MonoBehaviour
{
public float senseX;
public float senseY;
public Transform orientation;
float rotationX;
float rotationY;
private void Start()
{
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
private void Update()
{
float mouseX = Input.GetAxisRaw("Mouse X") * Time.deltaTime * senseX;
float mouseY = Input.GetAxisRaw("Mouse Y") * Time.deltaTime * senseY;
rotationY += mouseX;
rotationX -= mouseY;
rotationX = Mathf.Clamp(rotationX, -90f, 90f);
transform.rotation = Quaternion.Euler(rotationX, rotationY, 0);
orientation.rotation = Quaternion.Euler(0, rotationY, 0);
}
}
sorry my head slightly hurts
remove the Time.deltaTime from mouseX and mouseY
that's a common mistake. Even Brackeys got it wrong
https://unity.huh.how/mouse-input-and-deltatime
This explains why
I found this really good character controller and I'm trying to add a sword animation to it when ever you hit left click it plays the animation. But, when ever I try and do it, it just flashes for a second and only really plays when your jumping? Can anyone help?
I never really got vectory3, I know that you have x, y, z but the code I have completely changes how It is being used.
moveDirection = orientation.forward * verticalInput + orientation.right * horizontalInput;
move direction was given vector 3 and orientation is given Transform, basically what I'm asking is what axis is being used by what. Or what is is this line doing?
You can click the "Main thread" drop down to select different threads, but in this case it's better to use the Timeline mode to see all the threads. The one you're interested in is probably the "Job" threads.
Im currently developing a building system for my project and Ive been exploring methods to align the connection point game objects' positions with those of other game objects connection points, particularly for connecting two blocks side by side. Each block has six connection point game objects, one for each side of the block.
However, my current approaches are causing bugs and aren't giving the results Im going for. Im looking for advice on more effective methods to achieve this. Any ideas?
Let me know if you cant visualize what I tried to explain.
For what its worth, Im currently getting the parent of the connection point gameobject, calculating the offset between the connection point and parent, and the moving the connection point to match the position of the connection point of a different block that Im trying to build on, and then moving the parent to the connection point that moved using the offset.
so im guessing its rending a lot of shadows which is causing the issue?
Yeah. More precicesly it's probably just a lot of draw calls in general.
oh wait
A lot of objects to be culled.
like repeadly making instances
Repeatedly making instances in itself is not a problem. Having a lot of objects with renderers is a problem.
Especially if there's no batching going on.
It's hard to say anything beyond that without seeing more details, like the amount of draw calls/batches and your scene setup
I just make multiple instances of the grass prefab for each chunk once they are created
That doesn't really explain much. At this point we don't even know if grass is the culprit.
it def is because its only when i add the grass
it gets really laggy
else everything runs smoothly
Well, then you might want to think about batching or gpu instancing it.
alr ill look into batching
thanks
Then there are some other things:
- seeing how shadows seem to be one of the issues, consider disabling the shadows casting from grass
- consider changing the render distance of the grass
- consider the shadows options, like cascades and shadow drawing distance
- etc...
ok the thing is i did disable shadows from grass
wait js wnana make sure
in the player settings, i have to check the static batching
right
following up on my earlier question... I have a Calendar that triggers CalendarEvents. Triggering a CalendarEvent calls a member of type Action. I want to give the option for parameters for these events. I'm thinking of just giving CalendarEvent an ActionParameter member, so the method being called is of type Action<ActionParameter>. Then I can derive from ActionParameter as appropriate. In each event method, I will just do runtime type checking, e.g., if(!(param is typeINeed) throw new InvalidOperationException("wrong parameter type passed"); or something. Is this runtime type checking a bad idea? Any better alternatives?
Assuming you're using the built-in rp, yes, but that wouldn't work for objects you instantiate at runtime. Nor do you want a lot of grass to be static batched anyway. Ideally you want it to be gpu instanced.
If the grass had shadows disabled, then it must be something else that is causing it. Hard to say without seeing the rendering stats.
wait i think i fixed the problem
Not really specific to delegates, but once you start needing to check the type of every derived class, itll become really annoying and can likely be redesigned to not need this. Also it wouldnt make much sense to have a class be notified of an event, but then immediately throw an error because the type was wrong. It shouldnt have subscribed in first place.
How much can these parameters really differ?
keep iterating. Design atm makes no sense to me. It sounds like your Calendar is storing the parameters that it will eventually pass to the CalendarEvent. But why? If the parameters are already known, the thing that schedules the event with the calendar can satisfy them and the Calendar doesn't need to know anything at all
I'm not describing this correctly. Let me illustrate with some code:
class Calendar {
SortedList<CalendarEvent> _events...;
void MoveCalendarForward(TimeSpan amount)
{
//foreach CalendarEvent e in _events within time span:
e.Execute();
}
}
class CalendarEvent {
Action<EventParam> functionToRun;
EventParam _param;
void Execute() {
functionToRun?.Invoke(_param);
}
CalendarEvent(Action<EventPara> a, EventParam p) {
functionToRun = a;
_param = p;
}
}
abstract class EventParam { }
class Param1 : EventParam { int data; }
class Param2 : EventParam { string name; }
Then I can define CalendarEvents like this:
CalendarEvent newEvent = new CalendarEvent(Function1, new Param1(int1));
...
void Function1(EventParam p) {
//runtime type check
//do something interesting with p
}
and then in some other part of my code:
CalendarEvent otherEvent = new CalendarEvent(Function2, new Param2(float1));
...
void Function2(EventParam p) {
//runtime type check
//do something interesting with p
}
this looks good to me, aside from EventParam which is a useless class that adds nothing
how else would i pass in something to the function?
I think this is exactly what I imagined, I still have the same comment @tardy crypt
option A) CalendarEvent becomes a generic class that implements an interface
option B) CalendarEvents implementations are concrete subclasses created to do something specific
A is closer to your current implementation, but B would be my preference for cleaner code
Your Action<EventParam> + EventParam have basically just reinvented lambda capture, which is a built-in C# language feature.
yes, it would theoretically be possible to do something like assigning () => {capturedvariable.dosomethinginteresting} but I prefer making the information about the events explicit in this case
so perhaps CalendarEvent is abstract with an Execute function, and the subclasses just have their own parameter types and do whatever is necessary
Then you can still do it in a way that doesn't involve type checking parameters at runtime.
Instead of subclassing the parameter, you subclass the event.
yeah that is probably the most straightforward approach
By subclassing the event it's also just basically reinventing lambda capture, but eh if that's more of your style then sure go for it.
i went kind of crazy with lambdas and captures in an earlier project but they have their downsides. specifically, it's much harder to remove anonymous functions from a collection, it's much harder (impossible?) to obtain information about the captured variables...
and also captures have weird scoping rules
I disagree, because if you look at what happens to lambda capture, it just gets turned into a class with captured variables, so that's basically exactly what your CalendarEvent is.
can you actually access this class?
can i for example save it in the middle of a running game so that after the game has resumed, i can place all of the lamba information back intot he calendar?
No you cannot serialize them, sure if you need to serialize them then you'd need to use an actual class, but that wasn't a part of the original question.
But I'm saying that "it's much harder to remove anonymous functions from a collection" is not exactly a lambda issue, you can remove them just like you do with a class.
i mean if you hold the reference to the lamba, then you can remove it
but then you need to actually tarack that information
although i guess if i'm just adding "new calendarevent(...)" without a name, it's in the same place...
That's exactly the same with a class, if you want to remove it, you have to also track the class instance you want to remove.
true
But yeah I think that's a bit side tracked, sounds like subclassing the event should solve your issue.
thanks guys
maybe something like this:
class CalendarEvent {
public abstract Execute() {}
}
class CalendarEvent<T> : CalendarEvent
{
Action<T> function;
T param;
void Execute() {
function?.Invoke(param);
}
}
and then just define subtypes as:
class EventType1 : CalendarEvent<ParamType1> {}
class EventType2 : CalendarEvent<ParamType2> {}
where I need the non-generic CalendarEvent class because I have a SortedList of those and I can't do a SortedList of CalendarEvent<T's> with the generic parameter remaining unspecified.
The generic is not needed at all.
The parameter should be implementation details of the subclasses.
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/events/how-to-raise-base-class-events-in-derived-classes
Something like this should be good
Something like:
class AlarmCalendarEvent : CalanderEvent
{
private AudioClip _sound;
private float _duration;
// ...
}
class ReminderCalendarEvent : CalanderEvent
{
private string _message;
// ...
}
calendar.Subscribe(new AlarmCalendarEvent(sound, duration));
calendar.Subscribe(new ReminderCalendarEvent(message));
And calendar just needs to loop over the events and call Execute() on each one, without caring about anything.
ok fair enough, that looks good too
Alternatively CalendarEvent can also just be an interface instead of abstract class
right, though tbh i think the logic will be the same for each event type
other than the execute thing
And alternatively instead of having a CalendarEvent at all, just simply have Action, and you do:
calendar.Subscribe(new AlarmCalendarEvent(sound, duration).Execute);
Which will also allow you to pass in lambda directly:
calendar.Subscribe(() => { ... });
no, that second thing leads you down the dark path of wtfery even without considering trying to serialize Calendar at some point
that would be my opinion as well
Lambda just compiles to a class ๐
there's other state i need, like the DateTime that the event happens, whether it needs to stop the clock, etc
and you forgot it's a Calendar, so actually it's calendar.Subscribe(someTimeParameter, () => { ... }); and then you need to store that in the Calendar and sort it, so now you have a class to hold your lambda's time and lambda ... but you already have that, so it's a design fail
No?
You can very well have Action<DateTime> and you subscribe with calendar.Subscribe(dateTime => ...).
that's not... the right thing?
lol you need to think that through some more, unless you're going to execute all the events in order to try and sort them?
the date time is the parameter you pass to calendar to sort it in the calendar
the dateTime would be a parameter you apss to the method when it's called
but you'd have to already know that value to sort it...
Ah you mean you need to sort the events first, then sure Subscribe(dateTime, () => ...) and sort based on the parameter is no different from Subscribe(event) and sort based on event.TriggerTime.
you could do subscribe(dateTime, ...). i'd just prefer to have an explicit class to store the state rather than doing this kind of thing
lambdas are nice for some things but not explicit game state
anyway thanks again guys
It entirely depends on how autonomous the event is supposed to be. Is the event supposed to just be a handler that gets called without knowing when, or does the event also needs to manage its own call time?
But that's adjacent to lambda vs class.
Again, lambda just compiles to a class in the end. If you are writing a class just for capture and nothing else, then that's reinventing lambda. If you are writing a class for more reasons than that, sure that makes perfect sense.
Thanks again guys.
How can I "weld" one rigidbody to another so that they stick together as if they were parented?
Joints are no good for this.
Parenting basically disables collision for the child. (It's what I'm doing now)
I have asked this question before but the answer was inconclusive.
I really need this for my project, I'm kind of surprised there is no common way of doing it
Joint are the way to go. Alternatively you could make your own solution if needed.
Like adding forces
Again, joints, are no good. They have severe issues with tearing, and this is just not something I can accept in my case.
Short of making your own physics engine as loop said, you have been given all the choices already
Why do you need seperate rigidbodies then if you dont want them to act as seperate rigidbodies?
just have 1 rigidbody with children colliders, sounds like what you need
i see no part which needs to be a rigidbody
What?
So why do they need to be separate rigidbodies? And why does parenting not work?
Parenting would not disable collisions of course
Because they are objects completely independent of eachother until attached? I thought the video made that self explanatory.
I do parent them. The issue is, it doesn't properly apply collisions that way.
You do not need anything else than rigidbody and collision.
until attached
Yes, of course. Rigidbody and collision are the only two things expected of a system like this.
I fail to see the issue
The video made it very clear that they do NOT require rigidbodies after attachment. Imo
Are you suggesting to destroy the rb once attached? Keep in mind that they can be de-attached too. That might be a hassle to set up.
How is that a hassle?
Or swap the object
Well, saving all of the values and such. Is that the best option?
making it kinematic should be fine too
They are kinematic, and it has the issue of not colliding properly
What do you mean by "not colliding properly"
That has not been explained
One second
Then destroy rigidbody if it is not working
this is a separate issue then from what you asked initially. kinematic means its ignored from physics, its not going to handle collisions at all
it moves where you tell it to move, even if inside a wall
It sounds like this is the only way to go, okay.
Ah yea I just tested, having kinematic rb as a child still messes things up. You could have 2 versions of each part, one with a rigidbody and one without. Toggle either version when needed
This would just save you from storing everything you want about the rigidbody which probably isnt too much information
Destroying the rigidbody did the trick. I don't think I'll be messing with default RB settings for this particular game so it's fine to just add one back.
Thanks all.
I've been working on an implementation of the a* pathfinding algorithm, and it's been working as expected for the most part. I've configured it to avoid being near walls by putting negative weights near them, and positive weights in the center of the room. This works fine, but with anything bigger than a 1x1x1 cube, it starts running into issues with clipping, especially with dynamic objects (eg. doors). I've added a rigidbody to the mesh so that it should push itself away from objects it comes in contact with, but I think because of the forces that move it, it still clips through. Is there an approach I could take to avoid having the collisions happening in the first place or some other way of avoiding this behavior.
because the object rotates and you use path finding & physical system to move the object i.e. you move the object based on both geometric position and logical graph, unless your logical graph can tell the object the transform of obstacles (eg. navmesh) otherwise no way to solve.
to short: a set of vertices and edges cant tell you anything about obstacles in world space
Is there an API to multiply a Rect with a Matrix4x4 and get the resulting AABB rect?
My current code is just multiplying the four corners and then min/max the resulting points, which is kind of lame looking code.
there's a Vector4 * Matrix4x4 overload, maybe that could work?
Hmm, don't think that would work.
I guess I'm more interested in the implementation side of things, because yes, I'm aware that I'm not accounting for obstacle's places in real time, as I set what counted as an obstacle once during runtime. Should I instead find the path based on the edges of the object instead of the center, because that seems like what you're suggesting.
is System.Serializable data goes wrong if iam make it array? in my script iam already attach all component but when play the only component that doestn null was rigidbody other than that goes null. This happen when i make it array or list
public class DashAttack : AnimationAction
{
public float dashSpeed;
public float shakePower;
public DustEffect dustEffect;
public GameObject swordEffect;
public VisualEffect vfx;
public Rigidbody2D rb;
private bool isExecuted;
[HideInInspector] public float direction;
protected override void PerformAction()
{
base.PerformAction();
if (!isExecuted)
{
isExecuted = true;
CameraConfig.Instance.CameraShake(shakePower, 0.1f);
if (swordEffect != null)
swordEffect.SetActive(true);
if (vfx != null)
vfx.Play();
if (dustEffect != null)
{
dustEffect.PlayDustEffect();
}
}
rb.velocity = new Vector2(dashSpeed * direction, rb.velocity.y);
}
protected override void EndAction()
{
base.EndAction();
rb.velocity = Vector2.zero;
if (swordEffect != null)
swordEffect.SetActive(false);
isExecuted = false;
}
}```
probably, the vertices position and connectivity between vertices should be based on physical object just like building navmesh
why do I get this error Script error (ConstantMappersData): Update() can not take parameters. on a scriptable object
you mean making an array of DashAttack? this description is kinda hard to understand.
is this a regular plain c# class? it should be fine
you'll have to show code. scriptable objects also do not have a unity message for update
ik that, but i already changed the name of it, thanks ๐
yes, my DashAttack is like animation event that will trigger at frame n, so i use array for multiple dash. so all the component attached with inspector but when i play the game everything becomes null. I dont use constructor
debug what specifically is null, its probably just lost references from things that no longer exist. Also what is AnimationAction, is it a monobehaviour or just plain c# class?
plain c# class. already checked still it goes null when play
now the error fixed when i remake my list
what goes null? this is very vague. Surely you have some null reference error on something
iam using inspector for attaching the component like rigidbody, but everything fine except the dustEffect, but now it fixed after i remake my list.
im just dont get it what exactly happened, why it suddenly goes null even tho iam not touching the script at all
Hey guys, I asked a question on the beginner group but now that I think of it maybe Netcode is not so beginner. #๐ปโcode-beginner message
actually Netcode questions belong in #archived-networking
you are right, multiplayer is not beginner at all.
Ok, thanks!
Any indian? indie developer i want some help..
just ask about what you need help
breh
Also Indians and indies are different people.
I must be tired. this amused me Way more than it should have.
My internal voice went all Barry White
hello, i have a problem where my player is not accelerating to the disiered speed of 20. basicly its a dash script
these are the 2 main scripts
i used
Please, consider sending long scripts using the sites below. We have to download them if we want to fully see them, which is inconvenient
๐ 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.
Help with Unity Build Automation
I don't think so
Ayo, does anyone know why my game is stuck at 60fps regardless of the resolution or the target frame rate I set?
Ive also configured the default frame rate in project settings but it doesnt seem to have any effect at all.
void Update()
{
frames++;
float currentTime = Time.realtimeSinceStartup;
if (currentTime - lastUpdate >= updateRate)
{
fps = frames / (currentTime - lastUpdate);
fpsText.text = Mathf.RoundToInt(fps) + " FPS" + " " + Screen.currentResolution.refreshRateRatio.value + " HZ" + " target: " + Application.targetFrameRate + " vsync; " + QualitySettings.vSyncCount;
frames = 0;
lastUpdate = currentTime;
}
}
public void setResolution(int index)
{
Resolution resolution = validResolutions[index];
Screen.SetResolution(resolution.width, resolution.height, Screen.fullScreenMode, resolution.refreshRateRatio);
Application.targetFrameRate = (int)resolution.refreshRateRatio.value;
QualitySettings.vSyncCount = 0;
}
Everything else in the code is correct, just assume that validResolutions[index]; is the same as allResolutions
maybe you have VSync enabled?
not the case, i made sure to disable it in project settings
also its not my pc, I have a 144hz monitor and I am able to run other games at that framerate
Sharing your code is all well and good, but without any idea whatsoever of the data it is using that is, to put it bluntly, pointless
Its god damn huge to share the full code, i just picked the parts that have something to do with that
read what I wrote
Ye, I was refering to this
exactly, where is the data your code is using? Without it your code is meaningless
and what I wrote does not ask you to share more code
the data is the same
i have a filter i can toggle
so now its disabled
then the valid res are the same as all available res
like, the real problem is that the refreshRate is not changing, is there another funcion to do that, aside of the one i used in my code?
if i use a number lets say, 60 instead, something like this:
Screen.SetResolution(resolution.width, resolution.height, Screen.fullScreenMode, 60);
it still wouldnt change the Screen.currentResolution.refreshRatio.value
thats the problem
data is not important in this case, as it happens with any value
probably should have explained that since the beginning haha
hey guys i want to set the time of my animation to the float value in the script how can i do this
animator.SetFloat("AnimTime", yourFloatValue);
For some reason, first time I run a scene everything works. If I reload the scene, without any states being saved one script is just loses all its references. For no reason at all. I thought reloading a scene would reset everything. I can see the object in the active scene but "this" (refering to the object at hand is null. How is this possible?
Guys how do I make that some entities in my game spawn like in minecraft below some light level, I have scene (2D) and some rooms and how do I check if where entity wants to spawn there is light intensity 0.1? Do I need to make my own grid of light intensity or I can somehow grab it in different way?
Is there any way to detect a Unity button being held?
I'm adding mobile support to my project I wanna have it so the player shoots while holding a button but I can only seem to get it to happen when they let go
use a component that implements the IPointerDownHandler and IPointerUpHandler interfaces or an EventTrigger component to get the relevant events
Is IPointerDownHandler not for mouse clicks?
mouse click and first touch on mobile is synonymous i believe
if that doesn't work, there's always the EventTrigger component
with that, you dont need the Button component, an Image will do
Try adding Debug.Log statements at the start of your script's Awake or Start function to check if references are being assigned correctly after reload.
@prime sinew @somber nacelle Thank you both very much, I got the button interaction working on PC so all I need to do now is check it still works on mobile, I appreciate your help!
how do people store data of item with code to apply when equip? I mean in many tutorials, people just use scriptable object to store some UI data (eg. name of item, description) and never store effect inside it. I wonder how people actually do this? I want to execute a specific code in many item when equipped. My current idea is, I can extend class from a base class and make every kind of item. Is there any better way (not making a hundred different class)? Thank you.
can someone explain why my code is not working ?
I... THINK this is a question for this channel?
I have a world space canvas that has fog of war tiles and a ship that the player controls. (All UI images within the world space canvas group)
The ship has a circle collider 2D property and the fog tile have a box collider 2D component
My problem is, collisions aren't detected between the objects.
The video shows that all my fog tiles have 2D box colliders, my shipSight has a circle box collider, the script that's supposed to handle collision detection and log any detected collisions is attached to my shipSight object, yet I get no logs.
(Not sure what's making my fog tiles fade out when I get really close to them, probably some residual code I need to find and remove XD )
I'm going to guess, even though the Canvas is world space, because they're UI image, collision isn't supported?
A scene reload should just reset everything. This is just bonkers. Even more so, tracking the framecount on a specific event gives me this amazing result
How on earth is this even remotely possible. Notice the log time and the difference in framecount.
This event is fired ONCE on first load. Scene reload and same event and this happens.
How do you print it?
I don't think printing the frame count can give you a zero at the start
No you are right. That extra integer is a separate counter and I missed adding a space. I've given up on this. I will take another route. For some reason, reloading the scene does not reset the state completely. Things work as intended on first load but never on second. I have no objects set to DontDestroyOnLoad. There is no reason for this.
In first load that event is correctly fired exactly once. On second load the calling function is called exactly once but the event is fired 4 times within a single frame. For absolutely no reason at all.
If this is not an engine bug I don't know. I've never seen this behavior before.
Has be a ghost object being kept alive. I have no explanation for this.
Using sprite stacking, i need to make the parts rotate individually on the z axis and not the whole parent game object. But the parent, car in this example rotates on the z axis when turning. How can i make it so the part 0-17 rotation would match the cars.
I make animations with blend tree and I control the code in this way;
animator.SetFloat("xSpeed", playerMovement.movementInput.x, 0.3f, Time.deltaTime);
animator.SetFloat("zSpeed", playerMovement.movementInput.z, 0.3f, Time.deltaTime);
But when I do this, it plays cross animation at first and then switches to side walking animation. I want the side walk animation to play directly. How can I solve this problem?
foreach (GameObject go in allObjects) {
if (go == null) {
Debug.Log("Found a null GameObject: " + go.name);
}
}
try using this code
What do you mean by reloading the scene? You don't use DDOL though?
Thanks I already know which objects are null @noble quartz
@gray mural SceneManager.LoadScene
My humble take is that that method should reload the scene from scratch, as if I was starting the app again.
Why would you reload the scene?
In order to reset everything, which is the intention
I see, it should reload everything perfectly
Hold on, you said event?
Yes
Do you even unsubscribe it?
On reload?
Please, share the code with the event
Is there some C# attribute similar to [System.Diagnostics.DebuggerHiddenAttribute] that hides methods from unity stack trace ? HideInCallstack doesn't seem to work
Nevermind, had to toggle the console window's option
@gray mural if the scene is reloaded, are event subscriptions kept? The eventmanager and any subscribing object is destroyed?
Well, the event subscriptions are destroyed if the object with the event is destroyed
I have this bug now on the latest unity 2022 version (had it before)
After restarting the editor, it grays out one of my scripts, and gives me an error ingame.
Now i would just need to delete the script and add it again, it would work until the next restart.
What should i do? Do you guys think just renaming will fix the problem?
So it shouldn't be a problem if the script with the event doens't have DDOL, actually
Yeah, assumably
So you have a script A with the event. When the scene is reloaded, the event on the A has multiple references?
Well..
That's the same as DDOL
I haven't even considered this case
Anyway, simply unsubscribe EventManager's events
Also, consider doing it always to avoid this kind of issues, even if you're sure everything's under control
I will give it a try, this feels like at least a possibilty.
Well, this is surely the issue if your class is static
I was just wondering why this would happen if you say you don't have DDOLs
So unsubscribe in OnDestroy?
Yes, you usually subscribe the events in OnEnable and unsubscribe in OnDestroy
@gray mural well something changed! I still get two calls on the event for some reason though
But the missingreference is gone!
So BIG thanks!

That's the the thing to celebrate if it still doesn't work
Are all the subscriptions to the event unsubscribed?
yes
Could you send them all then?
Hold on I'm revering all the crap I've tried to clean it up
FACK
that was not it. Still losing references
What is that supposed to mean?
renaming the script fixes it, in case someone encounters the same, cheers
@gray mural the random lost reference that just happens seemingly between frames
basically what I'm trying to understand since yesterday ๐
How would I be able to understand it without seeing the code?
Granted
do you know exactly which variable is losing it's reference?
yes
show me the declaration of the variable
but thats the thing, even if I reasign it with FindObjectByType, some other object is also unassigned. And so on. I find it strange that a scene load comes with some state after reloading as everything works as it should on first run
public InterfaceControllerNFC InterfaceControllerNFC;
It loses its reference? How is it assigned?
originally in inspector
So do you assign it somewhere else?
ok. try this
turn this variable into a property. in the set test if the value is null and throw an exception if it is.
Dont forget to add a field:SerialzeFiled attribute and reassign in inspector if necessary
If not, then the InterfaceControllerNFC it references is destroyed
It seems to. Why that is the case is beyond me
I mean it is destroyed when the scene is unloaded but should be loaded as per first round on scene load
You cannot serialize a property with a setter
Need a break. Thank you for the help @gray mural the eventmanager thing was definitely something ๐
[field: SerializeField] public int MyProp { get; private set; }
this is perfectly valid code that serializes
unless you mean something else
you mean you cannot serialize a property with an automatic backing field, so add a damn backing field
No, SteveSmith mentioned testing if the value is null in the set. This kind of property cannot be serialized.
you absolutely can
You cannot
you can add attributes to backing field by using [field: target modifier on attribute
I'm literally using serializable properties right now
This property won't be serialized, as it implements a set
[field: SerializeField]
public int MyProp
{
get => _myProp;
set => _myProp = value;
}
No, that's not
you mean you cannot serialize a property with an automatic backing field, so add a damn backing field
I wasn't the one who said it
this property doesn't have automatic backing field
ok, sorry then, but that's who I replied to
and then you said you cannot
so I thought it was you
with automatic backing field you can, without just serialize backing field
Yes, the property with the automatic backing field can be serialized using field keyword
[field: SerializeField]
public int MyProp { get; set; }
The property which implements the get and set cannot
[field: SerializeField] // doesn't work and throws a warning
public int MyProp
{
get => _myProp;
set => _myProp = value;
}
you just replied to me saying you can't do that, so that was just misunderstanding
Yes, that was a misunderstanding. I haven't properly read their response ๐
Hey guys. I have a bit of a problem and I can't seem to find a way to fix it.
I'm working on an inventory system with different item categories (multiple classes), organized through inheritance. Checking if an item is a consumable, for example, is straightforward (if(item is Consumable)), but I'm struggling with creating a list of item categories an item must have for certain actions. I don't know if using a serialized list of classes is something that even exists. And enums have problems as they lack hierarchical structure. Assigning categories via enums (e.g., ItemCategory.Fish) has limitations due to enum's flat structure which will have no idea that the item, while it is a fish, it's also a consumable.
I hope I made some sense here. Would appriciate some help/design ideas. ๐
creating a list of item categories an item must have for certain actions
i dont think it is not gonna to work, you still need the class which holding the categories to implement the methods to call the categories in list
seems reimplement the same method everywhere is the only solution if multiple inheritance is prohibited, though composition can still be used in method body
public interface IFish(){
void Swim();
}
public interface IConsume(){
void Consume();
}
public class Tuna:IFish,Iconsumm{
public void Swim(){
SomeStaticHelperClass0.Swim(this as IFish);<--copy & paste
}
public void Consume(){
SomeStaticHelperClass1.Consume(this as IConsume);<--copy & paste
}
}
```the best way i come up with now
!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.
hey everyone, i wanna optimize the process of processing (chart)maps in my game
When processing a map with just over 1000 lines of text (so 1000 strings in the array) it takes around like 6-8 seconds but i would like to speed up the process to just under 3, anyone got any ideas on how to shorten said process:
no embed is crazy
You should first launch the Profiler and see where exactly the most time is spent in this method.
multithread the parsing, though json utility probably wont support multithread deserialize
also this https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.ensurecapacity?view=net-8.0
and use switch case, but that reduces little, probably none
you cant optimize the sort so the only thing you can optimize is deserialization
I see that you're deserializing the same payload twice but in a different type. See if there's a way to only deserialize it once, and switch on the type afterwards. An option would be to use a serializer that supports polymorphism, and have a single base class for the two note types.
NoteBase note = SomeDeserializer.Deserialize<NoteBase>(json);
if (note is TapNote tap)
{
// do stuff with 'tap'
}
else if (note is HoldNote hold)
{
// do stuff with 'hold'
}
parsing profiler data ๐
tyy
oh its that expensive? i see i'll do that then, thank you
ofc if you parse 50% of them twice, you are using around 2 seconds more
didnt notice that at first
Yeah it uses Reflection to put the values into class instances, and Reflection isn't the fastest
Hey people, first of all sorry i am not sure if i should publish this in code general or code beginner.
I have a doubt, lets say i have a MyPosition vector3, and have a OtherPosition vector3, i want to generate a new vector3, thats its in the exact same direction as OtherPosition (from MyPosition point of view), but at a specific distance, or within a range.
How could i do this efficiently? I have several ideas, like generating a vector3 converting to world to local position (from MyPosition point of view) and try to add or substract that vector3, but i really dont see that option very efficient.
I made a draw in ms paint to try to explain my idea better, its not very elegant, but i wish is understandable. Thank you all.
The picture just looks like getting a normalized direction vector and then multiplying it by the desired range
It's unclear if rotation of something matters or not because I don't see that shown in the image
Yes! in fact, what i want to do more specifically, its to make a kind of compass where myPosition would be the player and otherPosition would be the objetive
So yes, rotation would matter, at least from myPosition point of view
otherPosition would be static, most of the cases
You just get the local space position of the objective from the player's transform
Then use that to draw your compass
transform.InverseTransformPosition for the first part
Yes! i got that part, but now, what i want to know its to convert that local position to fit into a specific range/distance, like the part 2 of the draw shows, i thought i could simply grab LocalOtherPosition and subtract (or add) it with vector3.one until i get the desired position, with i think that would be performance expensive i am not sure, i wanted to know if there is a more efficient way to do it
{
Debug.Log("Loading level data for scene: " + sceneName);
if (File.Exists(savePath))
{
string encryptedData = File.ReadAllText(savePath);
string decryptedData = Decrypt(encryptedData, encryptionKey);
// Deserialize the JSON data into a single LevelData object
LevelData loadedLevelData = JsonUtility.FromJson<LevelData>(decryptedData);
// Check if the loaded level data matches the specified scene name
if (loadedLevelData != null && loadedLevelData.sceneName == sceneName)
{
return loadedLevelData;
}
else
{
Debug.LogWarning("Saved level data scene name: " + loadedLevelData.sceneName);
Debug.LogWarning("Saved level data does not match the specified scene: " + sceneName);
}
}
else
{
Debug.LogWarning("No saved level data found at path: " + savePath);
}
// No data found for the specified scene
return null;
}```
My sceneName is Level 1
My loadedLevelData.sceneName is Level 2
I'm not sure where I'm going wrong. Level 1 and Level 2 are both saving great if I never swap scenes. As soon as I do it can't find them. It's like Level 2 overwrites Level 1 data and visa versa.
normalize it and multiply by the range
Just use Vector3.MoveTowards
With the max range as the last parameter
Or clamp magnitude
localPos = Vector3.ClampMagnitude(localPos, range);
Is there a straight forward to exclude a child collider from being part of a rigidbody?
Basically I'd like to target a MonoBehaviour on the child that was hit, but it returns the parent (since it has a rigidbody)
What do you mean by "it"?
if you're using a raycast you can get the collider directly with .collider on the RaycastHit
Be specific with what you're doing, as different properties on RaycastHit do different things.
OnCollisionEnter, sorry wasnt clear
if you did .rigidbody or .transform you will get the parent
That gives you a Collision object which has the collider on it as well
Again make sure you use .collider if you want the collider you hit
.rigidbody and .transform will give you the object that has the Rigidbody
How would I make an editor script in Unity? Basically I want to make a script that I can run in edit mode, give it a file and then have it parse that file and do whatever else. I just don't know how to make it actually executable from the editor or how I would input the file that I want without the direct file path - I want to be able to input the file so that I don't have to go and edit the script every time I want to parse a new file
Still baffled Unity's abstraction for open and save dialogs is EDITOR ONLY???
Like, come on
That's pretty useful for a lot of stuff
At least there are 3rd party libs
think about it, open and save are platform specific and so dont fit well in a cross platform tool
Hi there! How its usually the "Game State" managed? For example while my character its in combat i don't want it to be able to open the inventory, or if a cinematic starts I want to disable every action map. Should the input manager (in my case its handled by a scriptable object that throws events) be told that the player is in combat, or that there is a cinematic going on?
Sounds like you want a state machine for your game
since you have these different "modes"
i want to make a active ragdoll character does anyone help me for that
start with the basics, work your way up
can anyone help how to make a dash counter like after 2 dashes it has to wait for the dash counter the recharge
i forgot that function but IEnumerator?
dont want a countdowntimer i want these two ui to go blank and comback after a certain time
i want a function that say everytime i do this then do this then if i do this again do this
you need a timer that's for sure
Which part do you struggle with specifically? Somewhere you probably have a dash counter, and then some UI script can do what you need
either do it in your update loop provided, or use a coroutine
i did something like this now i dunno how to minus the dashCount
dashCount--; to decrement (subtract 1 from) a variable
like this ?
Yes, though you need to use else if for the last if statement, otherwise it'll run both at once
Dash count is 2, subtract 1, dash count is 1.
Is dash count equal to 1? Well yes! Decrement again
i don't think that last if statement would ever be reachable if they used else if there since they return if dashcount is greater than 0 and if it isn't then they assign it to 2
Yo guys quick question.
Idk if its a bug or whatever but im starting on a new code for me game, pretty simple item pickup and i got
[SerializeField]
private AudioSource PickUpSound;
but for some reason in the inspector i cant drag the sound on the Audio Source field even tho its there, why?
this ?
AudioSource is the component that will play your AudioClip
Yes, but i need to add an audio clip to the audio source? Or am i doing it completly wrong
yea like u said dashcount 1 is not reachable
how should i fix it ?
What is this code supposed to do? Because the conditions are basically unreachable right now. Since you return; early if you have dashes left
right but your variable is for an AudioSource. this is the component that will be in the scene that plays your audio
Oh, my bad. Changed it to private AudioClip and it works now. Thanks mate
its supposed to make the dash channce disablle every time i dash so i got 2 chance to dash
thats what i a mtrying to do
i am quite new so i dunno how am i supposed to do so
Ah, so you should do this in the piece of code where you apply the dash to the player
Usually where you check for a keyboard or mouse input, however dash is activated for your game
How do i assign an AudioClip to an AudioSource? Since i got this in my code
public class ItemPickup : MonoBehaviour
{
public Item Item;
public AudioSource PickUpLocationSound;
public AudioClip PickUpSound;
PickUpLocationSound.clip = PickUpSound;
void Pickup()
{
InventoryManager.Instance.Add(Item);
Destroy(gameObject);
}
private void OnMouseDown()
{
PickUpLocationSound.Play();
Pickup();
}
}
but the console is giving me 2 errors
Invalid Token '=' in class,record,struct, or interface member of declaration
and
Invalid Token ',' in class,record,struct, or interface member of declaration
you have to do it inside of a method
Im pretty new to c# programming, what would that mean?
it means you cannot have logic directly out in the class like that. you have to do it inside of some method like Awake, Pickup, or OnMouseDown
Oh, can it be in Void Update() ?
Statements should be made in the method scope.
...clip = PickUpSound is a statement. Initialization on declarations would be fine but this isn't a declaration.
why would you want to assign it every frame though?
Yea, right. My bad
I did it in Void Start() and it works fine
Thanks guys
hay what are the best practices for implementing a status effect system?
for a turn based game (turn order system intended to replicate Honkai Star Rail's)
in my inexperience my best guess would be having an abstract status class with methods such as OnHit OnAttack OnDeath etc... and then when a character does something it would go through a list of all their currently applied statuses and run the corresponding method but this seems messy?
OnHit make sense since you can pass a struct of HitData that has a list of status to apply, but these other methods sounds like more conditional logic you want to apply
Rather, it depends on the behaviour of these methods as OnHit implies you have a target and you know the source unlike the other two
the method names are from the perspective of the character with the status for example say a status that makes the character do dmg to another random enemy when it attacks, or when that character dies it explodes or something, my system does allow me to see who killed a dying character so passing that information would not be hard just not sure if my way (of looping through a list of all statuses on the character) would be a good idea
I think it's fine for a minimal implementation, but the more unique logics that you implement the larger your script may become, but since it's just a turn based game it's probably fine
well you either loop through the current effects, or have them subscribe to some delegate. Looping through is fine imo
I think for the best type of modular design comes down to a list of delegates perhaps,
The thing I dont really like about delegates here is you already know exactly what you want to call the functions on. There is almost nothing else that needs to attach itself to this effect system
Like maybe a dictionary of delegates and have these dictionaries dependent on the passing parameters (does the delegate need a target? does it affect global?)
What are delegates?
function/method pointers with some c# sprinkled syntax
it also adds some complexity because now effects need to be removed from the delegate chain. While if you had a list of status effects, then just looped through them, when a status effect is removed its just no longer in the list
If this would be good for attaching other systems too that sounds like a good idea to account for say items or chatachter abilities with passives unless I just implemented that through the status system
Its hard to say really without knowing your entire setup. In my case, my abilities wont ever go through the same system as my effects system. Because my ability itself is notified when it hit something. In your case it can make sense
ultimately it comes down to grouping by parameters, some delegate groups are parameterless, some requires a ITarget, some require one or more ITarget
and probably much cleaner if you don't expect a return
if you used unity event, like button.onClick.AddListener, this is basically a delegate but unity's version. C# delegates are similar but different syntax. Another issue with delegates here is if you want to use a result from the method call. Im also considering how to handle this cleanly.
Lets say you have a status effect that makes the player take half damage. This is easy when you think about just a single function call. A method takes a float and returns a float
Doing this with delegates is still possible but when there are multiple methods all returning floats, they aren't added or multiplied together, you're just returned a single value from one of them. So now you need to handle this separately, which might involve looping through the list yourself.
I see thanks for all the help guys I think due to my lack of experience with delegates I'll just loop through a list of statuses when a possible condition happens and call the associated method, and as for items and passives I'll make them like unremovable invisible statuses
The way I would implement it is to have a class/struct representing all the combined stats (damage multiplier, is currently invulnerable, etc) that are computed with all of the status effects combined, each status effect simply takes in that class and returns a new one.
Actions like "do damage" simply look at the final computed combined stats and modify based on it.
Maybe even add tags to statuses for extra stuff like star rail for example likes to make dot effects have special interactions such being able to cause one to activate early, so I imagine they either have tags or a separate class that inherits from the base to identify dot effects or from a move that swaps all stat changing statuses
hi im coding my player basic input rn and i was wondering how to fix beeing faster if you move diagonaly. could somebody help me?
sry for interrupting
I think you'd use player input to just determine the direction they are trying to move then make a normalized vector out of that direction that you then use to actually move the character
yeah maybe i should go to #๐ปโcode-beginner ๐
I'll let one of the more experienced people chip in too cuz I'm also inexperienced and prob can't explain aswell as them
im doing this with my stats class, so stuff like damage multiplier or reduction is already calculated when the player picks up items. My case might be a bit different from JKLJosh's because i also planned to have rng effects like "50/50 chance to take more or less damage from an attack". not exactly what ill have in game but just an idea.
This is probably something i just need to think about more because i havent really designed what i wanted yet
ty
You can either store a chance alongside each of the stats, or just recalculate the all stats every time and have the calculation roll the dice. Latter is much simpler to reason about though.
While I could hardcode stats that are that common for less common things I wanted to have a robust system that could do anything between just not making you take damage, to something as specific as multiplying dmg taken by 4 then evenly distributing it to all enemies and allies in the fight
That shouldn't be very difficult with something that represents all stats
You would simply have a property that returns a final damage multiplier taking into account all the sub stats (which are the implementation details of all stats) and that's it.
Effects modify sub stats, actions don't need to care and just look at the final multipliers.
https://hatebin.com/zbqiisybkt
Here's my idea of some sort of modular delegate system
the very base of something to expand upon
may need a bit more logic to incorporate non-explicit values
The code is also extremely simple if you use C# record.
A record that represents all the sub stats:
public record Stats(
float AdditiveDamageAmplifier,
float MultiplicativeDamageAmplifer,
float DamageReduction,
// Whatever more stats
)
{
public float FinalDamageMultiplier => (1 + AdditiveDamageAmplifier) * MultiplicativeDamageAmplifer / DamageReduction;
}
An effect just takes in a Stats and returns a modified version:
class SuperStrongDamageReduction : IEffect
{
public Stats Apply(Stats stats)
{
return stats with { DamageReduction = stats.DamageReduction + 1f };
}
}
Each round you calculate the stats by applying all the effects:
var stats = ...; // Create base stats
foreach (var effect in effects)
{
stats = effect.Apply(stats);
}
And an action just takes in the stats and use the computed values:
void DoDamage(Stats stats)
{
player.Hp -= 10 * stats.FinalDamageMultiplier;
}
All Stats needs to do is to decide how to calculate the final stats based on sub stats, it doesn't need to care about effects or actions; an IEffect just needs to take in a Stats and return a new one, it doesn't need to know how each sub stat interacts with each other or which actions to apply; and an action doesn't need to care about what causes FinalDamageMultiplier to be 2.0, just apply it.
Also what's best practice for even implementing abilities in my case when a "move" is preformed it creates a MovePackage that gets pass around and edited through the move's logic, it holds data about what happened as a result of the move, who used it, who was targeted, the damage it dealt and any other chatachters who will take or heal damage from it.
kk
here is the code for my implementation of a move being preformed btw,
https://hatebin.com/rrljkfmudf
ive yet to use record, is it just so you can use the with keyword here? or is there some other benefits to it
(btw they are coroutines so i can pause them for stuff like animations later on or whatever)
im somewhat unsure what you are asking. it seems like a move in your case is the ability
yeah im asking like just if i went about it in a good way, like if there are any big flaws with my system, etc etc or if theres some super ovbious better way of doing it that is the like "standard"
Records have a few things that are very useful, for example in this record:
public record User(string Name, int Age);
- It has syntax sugar for constructor based on the properties you give it, so you can directly do
new User("John Doe", 42). - It also has syntax sugar for desconstruct, so you can do
var (name, age) = user. - All the properties are immutable.
- It has value semantics, which means
new User("Foo", 42) == new User("Foo", 42)will returntrue. This allows you to do comparisons, use them inHashSet<User>, or even use them as keys ofDictionary<User, ...>, without worrying about "oh no they have the same values but are references to different objects." withsugar, so instead ofnew User(oldUser.Name, 69)you can just writeoldUser with { Age = 69 }which is extremely convenient once you have tons of properties.
And of course, you can add members, methods and what not just like a regular class.
The last point is probably the most relevant to the code above, otherwise it gets very annoying to write.
thanks, from reading the docs i was kinda confused. I might try to rewrite part of my stat system to use this
Its kinda hard to tell, because its not really clear what a lot of these things are doing. Maybe consider making your own dictionary or other data structure for readability on that WeaknessHandler part.
Im trying to enable buyoncy in my game and i wrote this code:
public class Floater : MonoBehaviour
{
public Rigidbody rb;
public float depthBeforeSubmerge = 1f;
public float displacementAmount= 3f;
void Update()
{
if(rb.transform.position.y < 5f)
{
float displacementMultiplier = Mathf.Clamp01(-transform.position.y/depthBeforeSubmerge) * displacementAmount;
rb.AddForce(new Vector3(0f, Mathf.Abs(Physics.gravity.y) * displacementMultiplier, 0f), ForceMode.Acceleration);
}
}
}```
It works for the standalone scene with the water, but when I try making uit work in my game, the car just goes through the water. The same is for a simple cube (which floats in the sample scene). Can someone help me with why thats the case
seems like a magic number being used there with the position.y < 5f. Wouldnt you rather this work based on like a trigger collider, when the rb enters the water?
Also this should be in FixedUpdate with addforce. Otherwise, add debugs to see if this code is even running
The code is running
technically yeah but the water is always at 5f
ig i got lazy but ill do a trigger collider
I did a debug.log to make sure it goes in the if
yeah that was my biggest issue i knew the solution felt bad but I'm not sure how else id do it?, elements are currently just an enum, what ways could i do it better?
can someone tell me why the x value of the player's rotation can go more than 20
For starters share !code properly
๐ 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.
okay
heres the link https://hastebin.com/share/lamifeluha.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Okay. And how do you confirm that the value goes beyond 20?
when i play the game and i press the right arrow
it continues to go past 20 when i look in the inspector
What numbers does it show?
well the number is changing as i hold down the right arrow
Did you try debugging the intermediate values to see where the math goes wrong?
it just increases past 20
um no
i'll try that
I tried this and I still don't get it, when it prints the newRotation value after line 26, it shows that the value is still above 20
and it starts at 0 when i start the game
im going to ask in #๐ปโcode-beginner instead
Hopefully you aren't expecting these values to match the inspector
Edit: oh, didn't read that last message. Sorry
They will not generally match
Use Debug.Log or other debugging tools to see the values actually being used
why not?
That's how it is ๐คทโโ๏ธ
i did and it still goes the newRotation value going past 20
Gotcha, you should share the current code (with logs) in #๐ปโcode-beginner
I have a gameobject in a game and the gameobject is enabled at awake/start. How do I find which gameobject in the game is activating it? How do I log something like this?
Make a debug.log in OnEnable?
It is enabled probably from UnityEvent somwehere in the editor,
So not at runtime?
Not sure what you mean by that response
You might be able to find it by right clicking the obj and clicking find references in scene
Hey, I canโt see my project, I accidentally closed it out and donโt know how to get it back up. Any help?
Do screenshots, not pictures of your screen
But layout on the top right will help
Canโt, donโt have discord on my PC ๐
Or go to windows at the top
Hm Ok
You can access it via browser
Oh I see!! Ty!
Is there a Channel or identifying unity assets of some sort? I canโt find something Iโm looking for.
Just ask your question in #๐ปโunity-talk
Ok.
I think I can help but I think I might mess up.
!ide
Also code beginner
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
Oop sorry
I made a mistake before of not numbering my enums, now I wish to reorganize because I need to add new stats. Is there a way to keep the correct values serialized in unity?
I'm trying to use MongoDB with Unity but it keeps showing me that using MongoDB.Bson throws an error.
this is why I never will advance any of my assets
everytime I try to make something it eventually becomes unusable because of my changes
every enum I do make is in a bitwise format incase I do need to eventually turn it into one of those enum types
good thing im not too far into my game, i just manually went through and changed all the values. Only a few things used that enum
Is unityengine.object serilizable in a generic struct that is on a scriprable object?
If the struct is marked as Serializable, I believe yes. In certain earlier versions of Unity generics were also not Serializable so you had to make a concrete version
It is. It serialize a int and a string but the object wont
I assign the object from a objectfield in uitoolkit
If this is Editor, why not use a property field?
It was easier to use an objectfield than using that
Just curious., was there an official statement on the proceeding removal of support for VSCode? or am i just fully misunderstanding the state of things?
VS Code works, Microsoft has put out a new Unity extension.
Ok, misunderstanding it was then, it seems. thanks. i am using VS anyways, but i do use both. i consider it important that 'free'-er frameworks remain functional
Eh, depends on what you consider as "free" I suppose.
hence the quotes
C# Dev Kit is as "free" as VS is, they have the same license which is only free for individuals.
I'm not sure if the base C# extension works with Unity or not though, that one is actually free.
yeah, i fully understand the need to make money for developing these things, but i am borderline feeling nickel and dimed to death
Yeah it's a bit sad, for how much Microsoft wants to get rid of the "proprietary only" stigma of .NET, there is not even a free IDE that doesn't make you feel like a second class citizen.
well, at least the communities are keeping Codium and the other VS code based one (i forget the name. been sucked into a windows void) but, i think you have to use the MS license to enable plugin support anyways :/ IDK, it is a big subject ๐ I was just curious as to the future of VS Code and Unity. so, fingers crossed there is a decent one
[Flags]
public enum PersistentEffectFlags
{
None = 0,
Interval = 1 << 3,
}
[Flags]
public enum InstantEffectFlags
{
None = 0,
Damage = 1 << 0,
Healing = 1 << 1,
}
[Flags]
public enum EffectStatFlags
{
None = 0,
Damage = 1 << 0,
Healing = 1 << 1,
Duration = 1 << 2,
Interval = 1 << 3,
}
Not sure of the ideal way to go about this, but since we can't override enums my next best idea is just to cast them all to a main enum (in this case EffectStatFlags) for when I deriving multiple different classes.
Kinda seems janky seeing that I leave out some entires but I guess it kind of works