#archived-code-general
1 messages Β· Page 449 of 1
in editor you can pick what platforms managed or native libs are used on
Oh cool, where would I change that?
select it and check the inspector
I need the ones in the StreamingAssets to stay .net 9.0 , also selecting them in the folder does not show anything in the inspecctor
I guess this has something in the CsProj file?
Its probably because they are in streaming assets that normal options are there? Are you loading these in yourself?
these dlls are part of a seperate binary that I will run after the unity game has been exported
(it just starts a .net core api server)
everything works fine except getting these annoying "errors" in IDE lol
then lets presume vs code is dumb and thinks this dll is to be used even though unity wont
Yeah I think you're right.. VSCode might be getting confused from the .csproj putting those dlls in the file
tbh this doesnt even need to be in streaming assets if its just something you manage out of unity
well its because I want this to bundle with the game, so the game can start the API without user touching anything else or a seperate location from game
yea but you can surely write your own automation to copy a file next to the build output
hmm true maybe this is one of those convenience coming with this weird quirk to get around
see if visual studio does this or if you can exclude the file yourself in vs code (though may return when unity regens things)
yeah will give that a shot, thanks!
I wish there was some type of property I could use to ignore these in IDE :X
I'm having an issue where my unit's shooting will slowly start becoming in sync with eachother. They shoot automatically on a timer 2.5 times a second.
Here's my firing code
https://paste.mod.gg/kyggkxkhimfl/0
Heres at the start and after like 2 minutes (Left is after 2 min)
Sorry if I asked this wrong, first time asking a coding question here
A tool for sharing your source code with the world!
How can I start learning C# and learn using Unity?
check the pins in this channel #π»βcode-beginner
Hey, can anyone help me, im trying to do a 3rd person aim system and i managed to do it but the player shakes/jitters the more i move around, apparently i have a mismach with fixedupdate physicks and lateupdate cinemachine camera and aiming
Oh thank you mate
you have to show more info, nobody can help without
its possible that its a float imprecision thing Ohhh you mean they Sync together instead of falling out of sync ? think i read that wrong lol
Yeah they sync together lol
yeaaah ok I think i watched the first video thinking thats AFTER
Yeah I realized I uploaded them in the wrong order lmao
I wonder if its somehow waiting on a specific frame to instantiate them
I feel like it has something to do with adding to the timer not being continuous because delta time only gets added to the timer every time it runs through the script, causing each shot not to be shot at exactly 0.4 seconds.
and eventually they start linking up because of that? I'm not 100% sure how to explain that
would this be a fixed update thing actually?
is it using shootTimer or burstTimer ?
Shoot timer
how does it shoot with shootTimer? I dont see if statements for that
void FiringLoop()
{
if (shootTimer < 1/stats.attackSpeed )
{
shootTimer += Time.deltaTime;
}
else
{
BurstLoop();
}
}``` like here
only BurstLoop seems to call Shoot() , kinda confused on that
Oh ok
When shoot timer is greater than (for this unit 0.4), it call burst loop every update loop
When burst timer is greater than (for this unit 0), it shoots a bullet
When the burst amount is equal to the number of bullets in the burst (for this unit 1), shoot timer is reset to 0, restarting the loop
Ok it looks like swapping everything to fixed update and fixeddeltatime has fixed the problem
Thanks for taking a look at it !
these are my scripts but this causes the aiming reticle to shake and it gets worse if i move around with the player
here
- Do you have interpolatioin enabled on your Rigidbody
- This code;
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, turnSpeed * Time.fixedDeltaTime);is going to break interpolation.
yes
Then #2 is your issue
YOu cannot rotate the Transform directly or interpolation on the RIgidbody will break
Never touch the Transform for a Rigidbody
interpolation helps a little, if i disable it the shake gets worse
ok any suggestions how can i do this better
so add rotational force
I didn't say that
oh ok
so to clarify the issue lies in the playermovement script where im rotating the player
so the gunaimer and aimingreticle are correct?
I don't know. I saw what is definitely an issue in the rotation. I'm not going to rule out other issues in other scripts.
ok
PlayerRB.rotation = Quaternion.Slerp(PlayerRB.rotation, targetRotation, turnSpeed * Time.fixedDeltaTime);
i was thinking this then.
Start with:
PlayerRB.rotation = targetRotation; at first
just to rule out any issues with your Slerp
You are using a classic "wrong slerp" after all as well.
Applying lerp so that it produces smooth, imperfect movement towards a target value.
thank you :) i'll dive into this
hmm i should still use the late update for the gun aiming and reticle placement and fixed update for physics, correct?
yes
ok thanks :)))))
MoveRotation should be used instead if the idea is to not break interpolation
anyone know the SQLite4Unity library? i wanna implement a function to update the db when a user starts a newer version of the game, and there seems to be no function for ALTER TABLE ADD COLUMN beside connection.Execute(string, object[])...
Is there a way to change the "Sample distance" of the float array passed to TerrainData.SetHeights? I have the terrain at the size I want (let's say 5000x5000) and a float array with some smaller number of points (say 1000x1000). Right now, it's setting the height of a corner of the terrain to what I have in there assuming the indices are 1 world unit apart. Instead, I want those indices to be "fractions of width" instead of "real space units". Like, heights[0,0] spans an area of 5x5 in real space, instead of 1x1, since the width of the terrain is 5 times the length of the array.
Nope, definitely not in Update
You could do it by accumulating mouse input in Update and using MoveRotation but that's extra work
Setting the rotation directly on the RB works
I cant see their code on mobile so just assumed it is fixedupdate
Is there a clean way to convert a 2d color array to a 2d Texture? Feels like they should play nice but I'm not finding anything in the docs.
define "clean"
Generally fewest conversion of types as possible/ fewest loops as possible. Like I know I could probably loop through slowly coverting it to the 1d array for SetPixels but it feels like it should already be able to map 1-1.
Ideally just use a 1D array from the start and https://docs.unity3d.com/ScriptReference/Texture2D.SetPixels.html
whether you execute the extra loop/copy or some api does it for you, it still needs to happen
ahh Very sad. I'll just run my own conversion to a 1d array.
So - I've got an object moving, swaying side to side and up and down working really well, but I'm getting some weeeeeird jerky animation while walking/running, and my arms are disappearing.
Problem 1: I'm pretty sure this has to do with clamping the distance from the targetPosition GameObject (which is a fixed point attached to the camera). Has anyone dealt with that before? I think it might need smoothing? But I'm not 100% sure?
I'd say it's probably related to childing the camera and translating the transform and having desync on what is captured. If you haven't already, try sticking the camera in late update (if you're moving the transform directly), otherwise check out cinemachine
Hi hi ! I'm a complete unity newbie, and quite new to coding in general... If anyone is feeling gracious enough, could you lend a peek at my code ?
I'm making a result screen at the end of my level (for a rhythm game) and I'm wondering why it won't show up when music stops.
You only activate it if it's already active
why does removing the semicolon on the right give an error to my next line, but removing the semicolon on the left doesn't
https://gyazo.com/4b96d68d4767fdd16588a61af615a418
What's the error
did you copy paste the code from anywhere? my first guess would be one of them isn't actually the right unicode character you'd want ;. otherwise yea showing the error would help here
Hey, I was wondering if anyone here could help me figure out how to do some fancy grid movement using AronGranbergs A* pathfinding utility, I'm trying to figure out how to get an agent with a 2x2 node/cell size moving correctly but the solution on his site hasn't helped much, it only works well for 3x3/odd sizes :/
no i was typing it. the error jus says '; is expected'
it was just weird and i couldn't find out what i did wrong lol
yea thats odd, probably just some rare ide bug if it was both the same character
usually its better to ask asset questions in chats/forums specific to that asset. like if the developer has a server. this is also quite vague of a question
How do I activate my second pathfinder graph
I have all components on my object but it's not moving
There's only a forum which I've tried asking on but I only got linked to this page which has code to get 3x3 size agents working but it doesn't work for even sizes: https://arongranberg.com/astar/docs/multipleagenttypes.html#grid-shape
I was hoping I might be able to find someone on here who might know although I'm aware it was a long shot.
This page explains how to handle different agent types, such as agents of
different sizes.
isGrounded = Physics.Raycast(transform.position, Vector3.down, groundCheckDistance + 0.1f, groundLayer);```
Im using this to check ground below the player. The problem with this is Raycast is very thin so if the platform is narrow or the player is on the edge of the platform then it wont Jump when im trying to jump.
I guess a capsulecast would be able to fix this? any ideas?
will u guys prefer single object pool or multi-object pool, one pool handle one object or let it handle all the pool object?
one pool to one type
ty , i will keep it as it is thenπ
Yes CapsuleCast
@steady bobcat @somber nacelleI tried the same code as above βοΈ And now I don't have the error of yesterday anymore about the null reference, why is that ? π€ I tried to press play multiple times to try to reproduce the "null" error of yesterday but nothing comes out π€
(this is the screenshot of today's code to make sure that I'm not crazy that it's the same code as yesterday)
you're probably just getting lucky and the singleton's Awake is not being called before this object's OnEnable
I think all Awake()'s should be called then OnEnable()''s
Or yea its pure luck, which can be fixed with changing the execution order
https://docs.unity3d.com/6000.1/Documentation/Manual/execution-order.html
Awake is only guaranteed to be called before OnEnable in the scope of each individual object. Across multiple objects the order is not deterministic and you canβt rely on one objectβs Awake being called before another objectβs OnEnable. Any work that depends on Awake having been called for all objects in the scene should be done in Start.
I pressed play around 10 times now, and still nothing π I'm so lucky π€£
which is what i said yesterday
its not rolling per enter play session it's whenever unity decides to make that order again
i think?
actually curious how that onenable inconsistency works in practice
yeah the execution order typically does not change within the same editor session, i imagine that possibly restarting the editor can change it but i'm sure that regenerating the library would
that shouldn't be relevant for the thing you pointed out though right
probably related though? that doc isn't clear on the why's
which script is executed first is 100% relevant to their issue, right now the singleton is executing first so they aren't experiencing the issue because they are now accessing it after it has been initialized
So if I restart Unity, I will reroll my luck ?
maybe
Ok let me try that
that is really just an assumption, but anecdotally it does seem to be the case
including the hub or the unity session alone is enough ?
Slap this bad boy on the singleton with a negative number and you are good https://docs.unity3d.com/6000.1/Documentation/ScriptReference/DefaultExecutionOrder.html
(or set in project settings)
relying on specifying the execution order is not a great solution because it just hides bad design choices. though since they've reverted their code to the previously broken state it seems like they no longer care about digging out of their spaghetti mess so whatever π€·ββοΈ
defaultexecutionorder on a handful of select managers feels like a fair amount of tech debt to take on for the benefits in a smaller scale project
That's not true, it's just that I didn't write any new code since yesterday so didn't have the time to write a proper solution yet, but I just pressed play to test and it works and I got confused while yesterday it wasn't working π
I personally init objects manually to control order but in this case it seems ensuring the manager executes first is the easy solution
the easy solution would be to just make the events static like i pointed out yesterday. these objects are singletons so what is the point of using instance events instead of static events if they plan to just use a single instance of those objects anyway
Yup, got the error again, thanks π
I had the same issue with events being static
but let me try again
no you didn't because that issue is not possible if the events are static
oh then I'm remembring wrong, or maybe there's was another issue when I used static π
also the exception you've just shown doesn't even match up with the line numbers in the code you showed so wtf did you change this time
Let me check again
oh actually, it's from a different script entirely, looks like it's from your singleton's OnEnable
the thing is I have multiple Singletons
too many inter-dependent singletons 
there is not a single answer to that. but when they all rely on each other you're just building the biggest pot of spaghetti that you can
I must be italian then π π€£
though I don't understand that error at line 47 π€
it's the same thing as the other issue
oh ok
Guys, how the fuck do I set the light unit? There is no documentation.
All the ones suggested by intellisense are obsolete and don't work.
you mean intensity ?
No, I mean unit
to make sure it's in lumen because I am experiencing some bugs with that
try .lightUnit
intensity is set to a number higher than what I specified
what IDE do you use ?
nvm I'm an idiot
I referenced hdAdditionalLightData but not the actual light
you set a value instead of an enum ?
ah
glad you solved it π
WEll, I didn't
I don't get it
Using the Light and setting its intensity seems to be KIND OF a multiplier, but not really
I can't set the actual number in lumen
but for the HDAdditionalLightData, there is no method to set intensity that's not deprecated
I don't get it
then I don't think it's the unit that you need but rather the intensity, but I think you need to define the unit first for Unity to know what units are we talking about
π Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
π Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
'''
PlayerRB.AddForce(moveDirection * currentForce, ForceMode.Force);
''"
This causes my players body to also rotate which is not wanted, any tips on how can i do this better,
public class HeadlightIntensity : MonoBehaviour
{
HDAdditionalLightData headLight;
Light PointLight;
void Start()
{
PointLight = GetComponent<Light>();
headLight = GetComponent<HDAdditionalLightData>();
PointLight.lightUnit = UnityEngine.Rendering.LightUnit.Lumen;
}
public void SetLightIntensity()
{
PointLight.intensity = 50f;
}
}
Setting PointLight.intensity doesn't set it to that value.
However, there is no way to set headLight either intensity or unit. I don't get it
Lightdata has a SetIntensity overload that takes the intensity and the unit
intellisense says this is deprecated
and all other methods but I will test just in case
Does it not say what to use instead?
Yes, it does, and that other thing is also deprecated lol
but this actually works
so fuck intellisense
Peak Unity experience.
Iβd look at the actual code instead. Might be something in the comments about why itβs deprecated
On a related note, does anybody know how the fuck Light.intensity works? It's supposed to be a multiplier but it's...kinda not
Oh wait, so that mean that the value of 8 is the default value set in the inspector?
if so, then I didn't need to do all this in the first place
the default would be 1 i guess, not 8, because above 1 creates over bright lights i think
The value can be between 0 and 8. This allows you to create over bright lights.
this is what doc says
This is HDRP right?
well that's the problem, it's not. Setting the light intensity to 1 gave me a value of 12 lumens while my default value is 50
and also, that also means that 8 can't be the default value either
so I don't know man
yea
Where do you see the lumens?
There are three intensity values in HDRP. One is in Lumen, the next is a multiplier, the other is a multiplier for volumetrics.
The lumen one is handled by HDAdditionalLightData. I suspect the multiplier is the legacy intensity
I am looking at them in the inspector if that's what you're asking
But for the most part you'd just interact with it via HDAdditionalLightData, which is the API for HDRP.
ok ok so the way I'm doing it now is the right way, i.e. modifying the light data value
yea ok gotcha
Then what Wolfos mentioned. Check the hdrp docs:
https://docs.unity3d.com/Packages/com.unity.render-pipelines.high-definition@12.0/manual/creating-and-editing-lights-at-runtime.html
I was wondering if there was a way using simply Light and using intensity, but I guess I can't get a precise result that way
I see the first one as physically correct, the other two for artistic overrides
yea yea I figured it out, I just thought there was a simpler way, but there isn't
Especially when you want to control brightness and volumetric brightness separately
Question, how do I activate my second pathfinder graph
What's a Pathfinder graph?
A star pathfinding
Doesn't sound like something in unity by default
I would guess similarly to how you activated the first one?
Well I have no idea what you're talking about TBH
It's for a* pathfinding
You're going to have to provide way more details than that if you want help
You should assume that we never used that third party asset, so you'll need to provide some details about it.
It's built in
Is it?
Yessir
Then share a link to the documentation
U guys probably use navmesh
Definitely not
This is A* Pathfinding Project?
I use it
I still don't know what a "pathfinder" component is π
Oh shit is it a project
It's a third party asset
Lemme check
Yeah, you probably should start with checking what you're using.π
It's been years since I've touched it
From the question I think you may be referring to the graph?
You can't have two graphs active at the same time. So disable the first, then enable the second to switch
when I subscribe to something like this
void Start()
{
_cursor.OnMouseDown += () => _cursor.SetPosition((Vector2)WristObject.transform.position);
}```and this game object isnt ever going to be destroyed or disabled. Should I still unsubscribe?
I know if it was going to be destroyed then I'd have to do OnDestroy() { foo -= bar; }
but in testing, if Im going to play the scene, end playback, play the scene again, over and over again. will all those events remain subscribed?
if the lifetime of both objects is the same then it likely won't matter at all but it is still good practice to always unsubscribe to events
the only time the subscriptions would persist would be if this were a static event (which doesn't appear to be the case) and you have domain reload disabled. still better to always unsubscribe though
a subscriber component should un sub as it will still be invoked and prevent GC of the component and cause errors
whats the correct method to unsubscribe in? OnDisable?
if you subscribe in Start then unsub in OnDestroy
cool!
if you sub with a lambda then keep a ref to it to unsub it later.
yeah that's a good point to bring up as well, even if you write the lambda exactly the same it's a different instance created so it wouldn't actually unsubscribe unless you cache the lambda in a field and sub/unsub using that field
or just subscribe using a method group
I've cut out a lot of stuff that isnt relevant, is the way I'm using the event action good?
public class Arm : MonoBehaviour
{
[SerializeField]
CursorTarget _cursor;
void Start()
{
_cursor.OnMouseDown += () => _cursor.SetPosition((Vector2)WristObject.transform.position);
}
}
[Serializable]
public class CursorTarget
{
public Vector2 Point;
public event Action OnMouseDown;
public void SetPosition(Vector2 pos) => Point = pos;
void MouseDown()
{
OnMouseDown?.Invoke();
}
}```
Good event but yea better to use a member function (to sub) as its makes unsubbing easier
intellisense did it like that, which isnt what ive done in the passed, I normally use an event argument
whoops, i meant snippet
either way its not the way I'd typically pass a value into an event
i mean if MouseDown is supposed to be positioning Point (or i guess calling SetPosition), then it doesn't really make sense for it to be an event
Probably better if CursorTarget or the pos is the first event arg.
this would probably be better with a supplier, imo
its just to do this
think about what would happen if OnMouseDown was subscribed to by multiple classes, think about what that means
maybe that makes sense to you, but i don't know the context; from what ive seen i don't really think it does make sense
that touches on something im still a bit unsure on, ive heard people say a class should never exist in a way that only one thing can use it
there will only ever be one Arm instance that uses this CursorTarget instance
(well, there will be two different Arms each with their own Target, but they dont communicate)
well, i'll ignore that specific restriction for flexibility, perhaps
but should CursorTarget be able to have multiple "sources", in a way?
I have never heard such advice
given that it only has one action, MouseDown
its got _cursor.OnMouseRelease I ommited that as its called indentically to OnMouseDown
void Start()
{
_cursor.OnMouseDown += () => _cursor.SetPosition((Vector2)WristObject.transform.position);
_cursor.OnMouseRelease += () => _cursor.SetPosition((Vector2)WristObject.transform.position);
}```
and would you ever use 2 different targets for those separate actions?
like in the video, I need to reset the position when the mouse is down and released
why not have something like this
[Serializable]
public class CursorTarget
{
public Transform target;
Vector2 Point;
void MouseDown()
{
Point = target.position;
}
}
(i don't really know when you press or release the mouse in the video lol)
that moving gizmo changes color depending when the mouse is held or not
mb that its not clear π
public void Update(float dt)
{
MouseInput();
void MouseInput()
{
if(Input.GetMouseButtonDown(0) && !Held)
{
MouseDown();
}
if(Input.GetMouseButton(0) && Held)
{
MouseHeld();
}
if(Input.GetMouseButtonUp(0) && Held)
{
MouseRelease();
}
CursorLock();
}
Point += (Vector2)Input.mousePositionDelta * dt;
}```the target update method is like this, I know `MouseInput()` is a bit sloppy but I'll worry about it later
I was too lazy to dig through my files to find where I wrote that same thing in a much cleaner way
what's up with that update method
is this called from some actual component's update?
Arm is a MB class
Time.deltaTime is still accessible in non-components, but also, mousePositionDelta is already per-frame, you don't need dt
I cant use that, the game uses two mice at the same time, the input tools unity has dont work for me
Input.mousePositionDelta is only temporary just as I only need to test this with a single mouse
the new input system has multi player support: https://docs.unity3d.com/Packages/com.unity.inputsystem@1.14/manual/PlayerInput.html
multiple mice i have no idea though
I presume you can make your own virtual pointers in unity with this but i have yet to use player input myself
its just a custom mouse controller. offers mostly the same properties that the Input system does, just that I read it from a mouse class
Point += (Vector2)Input.mousePositionDelta * dt; becomes Point += _mouse.Delta * dt;
and later that MouseInput class will look something like this
void UpdateGripState()
{
bool gripButton = _isLeft ? Mouse.Button2 : Mouse.Button1;
if(gripButton && !_gripping)
{
HandleGripStart();
}
if(!gripButton && _gripping)
{
HandleGripEnd();
}
}```
InputSystem does provide device access too and is probably the better option moving forward
and has events to better get the device data
I'm not sure if it would have any way to understand how two mice work at the same time
plugging two mice in on windows, both control the cursor, but it switches focus on whatever mouse was moved most recently
if i move the right mouse, the cursor follows it and its like the other mouse becomes inactive. moving that mouse makes windows focus on that instead
its the same unity, just it switches focus each Update frame
what if you move both in opposite directions at approximately the same speed
when i do that on my device it basically takes the sum of the movements
and from what i remember, other devices do the same
You may be right, you can get all the devices and get the last active device of a type so im not fully sure how its handled:
https://docs.unity3d.com/Packages/com.unity.inputsystem@1.14/api/UnityEngine.InputSystem.InputSystem.html#UnityEngine_InputSystem_InputSystem_devices
it just makes the mouse jitter in place
trying to do it all via the old input system mouse pos seems kinda dumb though
True accuracy would ofc be using the os api to get the actual device data but hopefully the input system can cover this somewhat
that's what i expected, so there's not really any focus
it's just taking input from both mice simultaneously
the mouse delta that unity creates isnt used
this reads directly from the mouse driver
OH okay so this is all extra stuff not needed
I only use the input from unity right now as its easier for testing on a single mouse
well goodluck to ya
(its honestly a miracle in the first place windows mouse driver accepts two mice being plugged in)
functionally the same thing as a trackpad + mouse
it could have been designed to only allow input to be registered by the mouse that was plugged in most recently
because who is really going to ever plug two mice into a PC to use both together
so plugging in a mouse would disable trackpad automatically? that sounds like a pain lol
also it would mean you can't passively have a dongle plugged in alongside a mouse on your desk
I forgot trackpads exist haha
jokes aside, i think it wouldn't make sense that device drivers could only work one at a time for a given device type
having multiple printers available isn't unthinkable in even a basic computer setup
beyond that, multiple screens is very commonplace
and because laptops, multiple keyboards and mice are also common
plus bluetooth and dongle connections
so i think it definitely makes way more sense that device drivers in general allow multiple devices of the same type at the same time
-# not trying to argue, just thinking out loud, sorry if it comes off as that
yeah, I hadnt thought of it like that
Then you also have controllers with weird mouse support sometimes
oh damn controllers is definitely a really good example of why multiple devices need to be supported
theres something fun about using two usb mice to move two things around at the same time, and its surprisingly not that difficult to control like I had expected
Download a guys weird file from 2010 and get a wiimote in the mix π
wiimote as a controller for a unity game could be fun
this discussion reminds me of tom scott's emoji keyboard lol
fun watch about relating to multiple devices if you haven't seen it
That one guy played overwatch as Pharah with a baguette. Ensure your input system is ready for that
baguette is a type of bread and bread is square so obviously that's a key hence a keyboard smh
damn! they really got this using everything related to the wiimote
I cant see the speaker listed though π¦
oh, its in the "future changes" limbo
maybe one day if I find my old wiimotes, I might try it out
Why am I getting this Error? I used this exact same command in a previous script without issue and I am stumped why it is not working
the elements of notes were never initialized, they're all null
if you did the exact same thing then it probably did not work, or maybe sixteenthNotes was just empty so it never reached the part with issues
Am I not initializing the array on line 160?
that initializes the array, but arrays are initialized with all of their elements at the default value for the type. which for classes is null
pay attention to what i said
the elements of the array aren't initialized
Right, i forgot to do that, thanks
Why is my wheel collider doing... this?
The code is literally this:
private void MoveCar(float force = 0f)
{
foreach (Wheel wheel in _wheels)
{
if (wheel.IsOnGround())
{
wheel.ApplyForceToWheel(force);
}
}
}
public void ApplyForceToWheel(float force)
{
WheelCollider.motorTorque = force;
}
The car is currently lodged against an obstacle, but it starts heavily jittering when it drives. This didn't use to happen before, it randomly broke.
Doesn't look like anything is happening in this video?
I have a huge static class, that I only now realised must be an interface. Am I really lost, and I need to convert it to a non-static class?
For context, the class is an Eventbus, used across the whole game. I need a FakeEventBus for unit tests now...
Look at the collider visualization. It's spinning but jittering a LOT.
In this procedurally animated spider, the grey dots are the step targets for the legs. When the body rotates, the legs for some reason get closer to each other? How do I stop this?
{
Debug.DrawRay(transform.position, -transform.up * groundBodyRayLength, Color.red);
RaycastHit2D hit = Physics2D.Raycast(transform.position, -transform.up, groundBodyRayLength, level);
if (hit.collider != null)
{
Vector2 averagePoint = Vector2.zero;
foreach (Transform step in stepTargets)
{
averagePoint += (Vector2)step.position;
}
averagePoint = averagePoint / stepTargets.childCount;
averagePoint.y = averagePoint.y + bodyYOffset;
p = new Vector2(transform.position.x, averagePoint.y);
transform.position = Vector2.MoveTowards(transform.position,p,delta*posSpeed);
var targetRotation = Quaternion.LookRotation(Vector3.forward, hit.normal);
transform.rotation = Quaternion.RotateTowards(transform.rotation, targetRotation, delta * rotationSpeed);
}
}``` Function that rotates the body
{
RaycastHit2D hit = Physics2D.Raycast(stepTarget.position, Vector2.down, pb.groundTargetRayLength, pb.level);
if(hit.collider!=null){
Vector2 point=hit.point;
point.y+=pb.stepTargetYOffset;
stepTarget.position=point;
}
}``` Function that sets the step targets position to be on the ground
Does anyone know how precise accelerometer data i can get, how many decimal places
I am currently using Input.acceleration
Probably depends on the device. Have you tried it out?
yep, but i am only getting up to 3 decimal points
is there any documentaion , i couldnt fiund any
Is that not precise enough? For any input like that, I have normally had to smooth out the inputs to get anything useful anyway, so extra precision would essentially be eliminated.
Hey! Is there any way to change 2d Sprites when pressing a key? ( for example a tilting "animation" when moving iykyk )
unfortunatly not, i am trying to calculate position of phone in 2d plane
and the noise is also really high
Yeah, with that much noise, more sigfigs is just going to make it noisier.
Hello, I'm working with assetbundles and having an issue with static objects. My setup is each assetbundle contains one scene and each scene contains multiple gameobjects. I flag my gameobjects.isStatic = true then generate my assetbundle. But when I load it, nothing has the static flag - it's cleared?
Okay i really need some help, so i'm trying to do a system to switch between UI and do other simple action.
I have a class that is Serialized and hold every variable but not as MonoBehaviour so that in my main script can display it in the editor and also can instantiated as an array so i can do multiple action at the same time.
The problem come when i want to modify the editor so it doesn't show specific variable if some bool are not activated.
I'm using this code to get the target (i know it look empty it's just to give out an exemple)
[CustomEditor(typeof(UISettingsCompounents))]
public class UIEditor : Editor
{
public override void OnInspectorGUI()
{
var uisc = (UISettingsCompounents)target;
}
}
The problem is my target(class) doesn't have a any type like MonoBehviour or scriptable object, and i can't use one or else it won't show my class variables.
Is there any way to fix this?
target(class) doesn't have a any type like MonoBehviour or scriptable object
What do you mean? Isn't the typeUISettingsCompounents?
WHy is it a problem that it's not a MonoBehaviour or ScriptableObject?
I don't understand your issue.
Oh wait sorry I get your problem
[System.Serializable]
public class UISettingsCompounents
{
public GameObject uiWindow;
public Scene sceneToLoad;
public float loadDelay;
}
The issue is you're trying to write a custom editor. Those are only applicable to MBs and SOs
that my class that hold variables
What you want is a PropertyDrawer
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/PropertyDrawer.html
not a custom editor
okay well thanks
check the code examples there
DUDE THANKS
It as been weeks seriously
i think i drank so much coffe i must have missed the option so many time
you are a life saver
Been trying to implement multiscene workflow into my new project, and I'm struggling as it butts up against my existing workflow.
In my current workflow I create all UI at runtime, almost having exclusively empty scenes. So In a game like slay the spire or balatro, I try to create the flow: Start a run: Open the map scene, instantiate UI, pick an encounter, close map scene, spin up encounter scene, instantiate ui, close scene when it's over, enter a shop, do the same, etc. When not using multi scene workflow I typically have a sort of GameManager/GameMode class or FSM that manages the larger run in in one large scene, instantiating UI and closing at runtime as needed. With multiscene, the logic is separated into some permanently 'active' scene
My problem is, if I'm spinning up scenes additively at runtime, but keeping my logic scene the active scene, anytime I instantiate new objects they all get put in the active scene and at best I have to move them all to the scene they're supposed to be in, and at worst i'm switching active scenes away, instantiating, then switching back to my logic scene after instantiation is complete.
Feels like I'm struggling to make these two workflows work. Part of me thinks multi scene workflow just means "UI Scene, Gameplay Logic Scene, and Environment Scene". But I'm trying to make it properly multiscene by spinning up and down scenes as needed, but this whole 'active' scene instantiation thing is throwing me off. Any advice?
Wouldn't just childing the objects under the specific scene node fix those problems?
Can also make like master scene nodes that act as the root to the scene to instantiate upon
What do you mean by scene node in this case?
Just a general gameobject that each scene incorporates that stays at Vector3.zero
instantiating objects and parenting under things so their not just in the scene root yeah
Right I want to instantiate in different scenes at runtime, but I can't reference them at editor time because the scenes are empty at editor time. There's no gameobject for them to be parented under. Unless i'm misunderstanding
does this existing solve your problem
https://docs.unity3d.com/6000.1/Documentation/ScriptReference/SceneManagement.SceneManager.MoveGameObjectToScene.html
Haha yeah I was doing that as a workaround, but I just hoped there was something better.
Do you folks who spin up scenes at runtime ever spin down your scenes?
Is that where the root of my problems are, wanting to spin up and down scenes regularly?
Like if you were playing any multiplayer game, spinning up a new scene everytime you entered a match or something. Then when it's over, spin it down
I just treat scenes as a larger gameobject honestly
quicker to load and deload data, but that's about it
I can't concretely answer your question due to my experience but i'd wager it's likely a mix of you wanting to regularly spin up and down additive scenes + the fact you seem to prefer managing your scene's contents at runtime rather than in editor setup putting you someone against the common workflow Unity provides
Not that what your doing is wrong persay just maybe more niche
Though I might be mistaken but if your handling a majority of the games setup at runtime via instantiation I'm not sure which benefits of additive scene loading you'd actually be gaining?
I usually just prefer a bulkier prefab workflow than really juggling scenes.
I always wondered why scenes are mostly editor-only API where prefabs are both, I kind of prefer working in a similar workflow having multiple scenes managed at runtime instead of creating everything in the editor first (and then basically having to memorize the scenes build index instead of just referencing the scene as a object like you can with prefabs and the "new" input system)
I think itβs a bit of legacy stuff but also thereβs aspects to how a scene being kinda static compared to a prefab giving it more options for baking certain information and memory related stuff
eg. all prefabs you have access to at runtime are loaded into memory where-as scenes are only in memory when they are loaded
I do personally use little scriptableobjects as a kinda wrapper for hardcoded scene names for the reasons you mention
Scenes do in my opinion work better with assetbundles when you do want some constraints on what is loaded
I can understand if theres some memory management with scenes, though I do think there should be a way to at least reference scenes or have a better organization system for the Build Settings window - using SOs as a wrapper sounds like an alright workaround for that (assuming the scene names dont change often)
yeah scene reference entry point is a big pain, but I think batby did bring up some methods around that
Godot gives you that entry point, so you know exactly the first script to access when you do load those scenes
Otherwise you got to use Find, or have some subscription system the scene callbacks to when loaded so your gamemanager grabs
this can be nice sometimes too
https://docs.unity3d.com/ScriptReference/RuntimeInitializeOnLoadMethodAttribute.html
Interesting, for one project (im still experimenting with so im not sure how reliable this approach is), im using a scriptable objects OnValidate to access the Build Settings editor API to try and get all the scenes and giving them a specific naming convention to store at runtime, so if I change a scene order or name, itll get updated after forcing the SO to "Validate", which also seems to happen before a build starts, though a lot of strange editor code to do it
Is there an ideal place to discuss suggested changes to the docs? Found a super niche solution to a problem i've been searching for for ages and it's seemingly completely undocumented
I am attempting to rig my character which is located in a different bundle onto, could this be done possible with a string path code? Not have any success with the following code.
0 SkeletonBone data
1 string m_Name = "Body"
1 string path = "sharedassets0.assets.resS"
1 string m_ParentName = "CC_Male_Rig(Clone)"
0 pair data
0 unsigned int first = 2073732236
1 string second = "Body"
1 string path = "sharedassets0.assets.resS"
I think there's an option to make suggestions right in the docs. Somewhere at the bottom of the page I think.
Other than that, maybe make a post on the forum
ah ok, sounds good
if your curious btw based on some testing it turns out the documentation on this attribute is kinda wrong, BeforeSceneLoad and AfterSceneLoad are not callbacks for the first scene but instead callbacks for any scene loaded before the first scene is loaded. Which means if you load scenes in an earlier callback you can recieve those scene callbacks for any scene of your choosing
Hey guys not really sure if this is the place to ask this, but I'm having trouble initializing the camera using XR Origin. I'm creating the camera object and is has the movement controls which are working. The objects in my scene are appearing just not the camera feed. I'm sure I misconfigured a setting somewhere I'm just too new to know where. Thanks in advance gusy
``` I believe this is the issue
Hello, i was wondering if there are any downsides to a method ive been playing around with compared to using just JSON for in game settings. This is the code i'm playing around with but maybe theres something bad with using a scriptable object here or just this approach in general? I havent seen it before so thats why im unsure, im just playing around with different ideas: ```[CreateAssetMenu(fileName = "GameSettings", menuName = "Game Data/Game Settings")]
public class GameSettings : ScriptableObject
{
public float masterVolume = 1.0f;
public int resolutionIndex = 0;
public bool isFullscreen = true;
public void Save()
{
PlayerPrefs.SetFloat("Volume", masterVolume);
PlayerPrefs.SetInt("Resolution", resolutionIndex);
PlayerPrefs.SetInt("Fullscreen", isFullscreen ? 1 : 0);
PlayerPrefs.Save();
}
public void Load()
{
masterVolume = PlayerPrefs.GetFloat("Volume");
resolutionIndex = PlayerPrefs.GetInt("Resolution");
isFullscreen = PlayerPrefs.GetInt("Fullscreen") == 1;
}
}```
More of a question of Json vs PlayerPrefs really
it wouldnt look exactly like this obviously, its more of a template for how im thinking
okey, i see
but theres no immediate badness so to say about it?
Assuming you're serializing them into other monos on the editor then it's preferred, otherwise a plain c# class would work fine too
okey, that sounds good, this is just templating so far but that helps, thanks!
nothing too special about SOs besides the fact you can move them around the editor
yeah thats fair, i just want something quick up and running tbh, im probably going to switch to json when other more important systems are done. This was mostly me wanting to try some new features to learn new stuff π
thanks for the help!
I would avoid scriptable objects here because this might give you troubles later on. It's usually advised not to modify values on an SO unless you know what you're doing. If you modify them in a build, it might reset if nothing references that SO
So ate moreso designed for static data
Things like stats for enemies etc.
That are consistent through all play sessions for everyone everywhere
You CAN serialise into jsons and stuff but like
If you are doing that⦠just use jsons
If you are not aware, when you close the game if you have changed the data in the so at runtime it will not βsaveβ and will just revert to default values
It should save. The only large problem with player prefs is the values breaking when updating the game, but other than that this seems fine to me
That doesnt seem to be an issue here, hence the save/load methods. The real issue is what I said above, if nothing references the SO, it might be unloaded
Oh sure in that case why use so at all tbh
Does anyone know the a star pathfinding project
I need help with a script in my project
ok
Could u help
you should learn how to !ask a question π
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #πβfind-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
I have it as a manager in DontDestroyOnLoad, that should be enough right?
but yeah, i can see why its good to avoid, ill play around with it for fun but JSON seems like the simpler and better solution tbh. Good discussions tho, interesting points.
Can anyone help me with a star pathfinding
Don't Ask To Ask
but also if it is with a specific asset you should probably seek that asset's support community
If you have specific questions you should ask https://forum.arongranberg.com/.
There's also a Discord, but questions don't really get answered there (kind of a blind leading the blind situation).
don't set the destination every frame, set it every X amount of time (where X is a high enough number that you aren't causing the agent to constantly recalculate its path but also low enough that it's not incredibly obvious that it isn't tracking the player each frame)
i usually go with every half second or so in my prototypes
i have tried this:
InvokeRepeating("MovingToLockedPlayer", 0f, 0.5f);
did not help
with no context i could not say why that didn't work
but that's also not a great way to handle it anyway. a simple timer in Update is sufficient
it is also strange that agents work perfect in other areas with no obvious surface difference
well if you have confirmed it is the surface then wait for an answer in the ai navigation channel because it wouldn't be a code issue.
do you mean there is some callback?
what? how is that even remotely related to what i said? i said that since you have confirmed the issue is with the navmesh surface then you need to wait for a response in the #π€βai-navigation channel where you forwarded your question from. this is a code channel, if you have confirmed your issue isn't in the code then it does not belong here.
i have not confirmed anything
well this points to it not being a code issue if your code is working perfectly fine on other surfaces
Is foreach still slow in unity?
foreach is not slow in Unity and I'm not sure when it ever was.
slow might be farfeched, but i mean slower than iterating with indices
Maybe you're thinking about some years in the past in the Mono runtime when some of the built in collections might have allocated GC but that was fixed like 10+ years ago
foreach may still be slower than a regular for loop but it's most likely not considerable enough of a difference to matter. Use the profiler if you are having a framerate issue.
yeah, it's not a big issue. in this case it's taking 0.02ms. The reason im optimizing this is because it's part of recursive code that might have more than 2000 layers, so it adds up
Are you profiling in builds? IL2CPP will have different performance characteristics when it comes to this sort of overhead.
true, i guess it's time to move back to builds
that's 0.02ms for all 40 calls. 0.0% of your overall frame budget.
You should focus on something more impactful to your framer budget.
You can also just switch it to a regular for loop and see what difference it makes if any
If it's for edification
in this small scenario it's 40 calls. Had to go for a small scenario or otherwise these small things are too deep on the hirearchy to even find it
that deep of a call stack is potentially bad too - you might want to consider refactoring a recursive operation into an iterative one. I think 2000 levels deep threatens to potentially cause a Stack Overflow on some platforms, depending on available memory.
Oh god yea that may be too much
So far, I have a class that manages that so I can, via a set of checkpoints, go X amount of levels deep, in an out
Since it's a treelike structure it's hard to move it into an iterative process (if it's even possible) The way it's built I have the trunk of the tree and say, give me the data! and then it goes through the tree as many levels as needed until i get one single output result
Anything you can do recursion can always be done iteratively using a Stack
it's always possible
It's not so much about being possible, but more of the complexity and the cost that it introduces
i feel like if your profiling a foreach loop you might already be in those complex waters already π
that's true hahahaha
It's probably not as complex as you think.
Here's a quick drawing of a really really simple graph. Every block is a node and it's a graph editor, aka, they can be arranged in many ways. Special notes apart from the simple ones, the red is a branch, meaning left or right is evaluated depending of another branch (that i forgot to draw). The big square with many arrows is a dettached node that doesn't follow the branching but generates data as requests are done. And the square with squiggly line is a node that first gets data of a branch, calculates, and then gives that data to the first node of another branch to then calculate more data.
If i had to iterate over nodes i need to:
- Go from left to right to get the order of all nodes, and so going through all depths
- Go from right to left (somehow knowing exactly what is a starting node and what isn't) but then there are things that I can't do, like branches for later nodes
if I go first from left to right to get the order, and then start iterating it's possible, but the issue of going through all depths would still be there
there is literally nothing that can be done recursively that can't be done iteratively. This description you gave is really vague but graph traversal is a very well trod subject.
You might not want to refactor, that's fine
I'm just pointing out that if you find limits with recursion, the option is there.
Think a game like slay the spire, or any other roguelike deckbuilder where you have a run comprised of multiple smaller runs. Each run is comprised of unique encounters and unique bosses.
Please talk me out of trying to build a hierarchical state machine for this. Please tell me an enum based state manager is good enough, I don't even need the state pattern... Right?
Obviously, you cannot represent a whole run as an Enum... It contains multiple data, not just a single value.
And you do not need it to be hierarchical same if it would make sense. However, using enum to represent each state is not a good idea even if you only use it as a way to switch between them.
I'd like to sort a number of gameobjects in the hierarchy by their world position (in this case Z), because they have UI elements. What's the best way to re-order gameobjects - detach them all from their parent and re-add them?
SetSiblingIndex() on their transform
Hey, is there a way to give a name to each enum entry that will be displayed on my UI in game without having those underscore or it being uppercase please ? And without creating a method that takes that enum, to PascalCase it, then remove the _ symbol.
I want to see first if there's something that does that directly without me coding all that stuff π
Like the same thing I did with the attribute [InspectorName("Task Name Here")] but I want for the stuff in game
Yeah but I want to know first is if there's a way that does that for me first like the way "InspectorName()" attribute does
To display it in the same format as the ones I put in |InspectorName()]
like for instance in Unreal, there's an attribute called DisplayName(), so it does all that complex stuff behind the scenes for you
so I don't have to write my own method to do it
you want to.. extract the value specified in InspectorName..?
if this is user facing you probably shouldn't rely on that behavior anyway, especially if you intend to localize your game at some point
(though im pretty sure you don't actually need any of those InspectorNames)
I need it for the inspector part
For in game UI you would need to write the mapping yourself. Use a Dictionary or a switch
unity doesn't show the raw enum names. it turns them into Title Case, which is exactly what you've done manually in the InspectorNames.
Write a property drawer for it
a property drawer for it ?
ohhh wait enums are usually in pascalcase already lmao
If you want the value on your UI, then you can use a bit of Reflection to get the attribute and extract its string property
yours happens to be in macrocase so you had to specify your own names
Yes
oh, I got that style from coding on an UGC platform, so the norm of enums is PascalCase ?
Are you talking about the one for my UI or for the Inspector ?
It's funny you say enum based solutions aren't great, because it's like all over the internet. Everyone uses enums to manage state it seems
Inspector
That was my next question, what's the proper way to do this type of stuff if I need to locolize my game later ?
pretty sure the suggestions in the enum members would tell you that
Then No, that part is already solved thanks to Odin + InspectorName attribute
Except that that isn't reusable in the game
So it'd make sense to make some mapping code and use it in both places
Yeah, hence my question but I need both anyways
Rather than duplicating the mapping which can go out of sync
nope it just tells me that's it's not used π¬
huh
Oh yeah, but I also need to think about localization, what's the proper way of handling texts in a game to make your life easier when doing localizations ?
-# my ide always screams at me for not following convention π
but yeah enums are typically PascalCase
if you do that you get the inspector names for free
There's a package for localization
what about the _ symbol ? Does it understand that it should be not visible in the Inspector ?
well clearly not lol, as seen in your "before" screenshot
but you wouldn't use _ in PascalCase
What's the name of it ? How does it work ? And what's the way to solve the out of sync you talked about / what's the proper way ?
it's called localization
How does it work ? Like is it like in Unreal where Unreal grabs all the strings present in your game and give you that list and you can use the localization tool to translate each of them ?

I'm scared to do a mess with it π
do you have vcs?
It's a whole thing you should read about and learn
With lots of tools for different use cases
It's not simple enough to describe in one sentence
if you have vcs, you could just make a branch
I have it but I use Rider
He's talking about version control
Not visual studio
I.e. git
Or UVCS
Alright, do you have a good youtube tutorial about that please ? π
No
Oh yeah I have that but I'm really bad with version control π¬
You should practice and get better. It's an essential skill for making any kind of software product like a game
I agree
If you mean the following, then it is obviously bad whatever the rest of internet means.
public class Gameflow {
public MyStateEnum currentState;
public int XStateSpecificData;
public int YStateSpecificData;
}
if you mean, then it can work depending on your use case. (I.E. you reuse the same state over and over again.)
public abstract class State {}
public class Gameflow {
public Dictionary<MyStateEnum, State> states;
public State currentState;
}
However, in your case I would simply recreate my state each time and keep whatever logic that needs to be share elsewhere. By example, you might have a "Run" class that represent the current run. I believe it is better because you might want a run to outlive the actual "execution" of the run.
Hello, I have a small problem and I need help.
In my Unity terrain the FPS drops drastically when I add grass, in this case I am adding it as if they were trees with the tools
My grass is composed of 3 planes that render a texture of the grass and the shader is in charge of giving it a little movement
Now, as I said, the performance drops a lot and the draw calls increase a lot and I don't know how to instantiate the grass on the GPU because, as I said, there are 3 planes that make up the grass.
These Planes are children of an object that has nothing, so they are not a complete mesh
how can I make AudioSource.PlayClipAtPoint work in 2D? the sound is all quiet
it works the same in 2D and 3D. No difference
make sure you have an audio listener in the scene, close enough to the chosen position
and make sure you haven't disabled sound in the game view window
but like my other sound from firing a bullet is normal while the playclipatpoint (using ti cuz I have a gameobject destroy for the bullet) makes it all quiet
like its there
just barely audible
Probably because it's further away from your audio source
or it's a quieter clip
Ive tried it with the same exact clip and setting the location to my players rigidbody
You'll have to start showing code/screenshots/videos
also the inspector of the audio source you're comparing with would be nice to see
this is what im using for the playclipatpoint
its on my bullet script which usually would break the bullet on trigger which it does
but I heard that because im trying to destroy the object a normal audio.Play() wouldnt work so this was my solution though its quiet
You'll have to show what we're comparing it to
then the OG clip which just plays upon firing
also what are you passing in for volume
make sure it's set to 1 in the inspector
In this case, what did you assign to audios and can you show the inspector for it?
had it set to like 25f earlier, setting it to 1 didnt change anything
ive heard that this problem might have to do with the spatial settings of PlayClipAtPoint being set to 1 which is usually 3d
though not sure if that is the problem and if it is how to set it to 0 (2D)
Yeah that could be it for sure
I would say one option is to just play it at the z position of your audio listener
i.e.
Vector3 position = transform.position;
position.z = mainCam.transform.position.z;
AudioSource.PlayClipAtPoint(clip, position, volume);```
Okay! Worked wonders thanks. Last issue with this is that the sound does now change based on distance which ig I can work with, is there a way to make that universal?
I know that is literally the entire point of this method
but it works with destroy so
just play the sound always at the audio listener's exact position then
instead of the position of the object that's exploding
PlayClipAtPoint(mainCam.position, ...)
that makes it work no matter the distance, but the sound is all messed up now. Might be playing twice? not sure
oh wait hold on got it to work
thanks for all the help!
Yo yo just generally asking how do you guys save game data in unity? do you just generally use player prefs for everything?
The opposite
most people will just use json. there are tons of tutorials out there on how to do this
gotcha I'll check that out. thanks!
json's a pretty cool guy
yeah I love JSON
Hey guys, how would you write code for the following kind of structure? Or if someone has a recommendation for a better structure in the first place-
class CreatureStatemachine;
abstract class CreatureState;
class PlayerStatemachine : CreatureStatemachine
{
public StunState stunState;
public ProneState proneState;
[Serializeable]
public class StunState : CreatureState
{
// Requires access to the creature and the statemachine
}
[Serializeable]
public class ProneState : CreatureState
{
// Requires access to the creature and the statemachine
}
}
Should I just expose a field to manually assign the creature in each state?
Or would it be a good idea to assign those things in the constructor as the field gets initialized? Nvm forgot that previously I tried this, but this cannot be passed during field initialization.
Could you do something like this? You can pass "this" in as a parameter to a constructor. I wouldn't want to set this up in the inspector
Me neither... Although I can't initialize the entire state like that since... I use Serializable classes to assign values in the inspector
I could however take a very similar approach and only initialize the necessary fields via a function or so
Yeah, it's decided then, thanks!
Yeah I think you are right, if you don't have a constructor then I would just add an initializer function to each state and make that part of the abstract class.
is there a built in Unity system to turn a string into a camelCase or PascalCase format ?
Are you referring to within the Visual Studio Editor or Unity Editor/ Inspector?
I mean in code
so not in the Inspector / Unity Editor
You'll need to ask a Visual Studio support server. Highly doubt it, natively, but perhaps there may be tools or whatnot to accomplish what you're needing to do. The Visual Studio Editor and it's environment is unrelated to Unity (other than allowing you to create scripts with Intellisense etc)
why visual studio ? I'm using rider, and here I mean a method or Utility class to format string
Or a server related to whatever ide you're using
I think you don't understand my request because it has nothing to do with an IDE π
What's it to do with then? Anything outside of the Unity Editor is beyond Unitys control
this type of thing is very simple to implement, if you couldn't find any builtin utility methods with a quick search, then you should just implement yourself
especially true if you already know the original format that you want to convert to any other case
Are you familiar with the .toUpper() for strings ?
The language and string class isn't a Unity type...
i never said it's a Unity type π€
Lookup the ms docs for the string class or ask !csds
Join the C# Discord server, a programming server aimed at coders discussing everything related to C# (CSharp) and .NET. https://discord.com/invite/csharp
like I'm look for something like .toCamelCase() and .toPascalCase() if it exist π
to put it simply π
it doesn't exist, but you can look up how to format strings like that yourself and write extension methods for it
hello. i'm attempting to open an older project and i can't find the jobs package in the package manager. was it remove or changed?
Howdy folks. My game has a few spells the players can cast. These have their behavior determined by a scriptable object, which has an array of a "Module" class which has info on one type of property the spell has.
Would it be best to replace the "Module" class with scriptable objects that have the same info? Or is there some other way to organize this better? I want to work on my separation of concerns and such.
how can I call my players x movement direction wtihout ti changing?
Using a knockback function which deals knockback based on the Input.GetAxisRaw("Horizontal") but lets say I move left and hit my enemy (which is to the left of me) the enemy will be knocked back towards me since im moving left
How can I get it to just deal knockback in the opposite direction of where I am in relation to the enemy
and when im standing still the knockback will just go straight up
this is the function call
Seems like you've got variables to handle that, hitDirection and constantForceDirection. You probably want to change those based on where the player is relative to the enemy rather than what direction they're facing. Where do you calculate those?
its meant to still deal knockback even when the character isnt moving at all
just not sure if the Input.GetAxisRaw("Horizontal") will do the job for the inputDirection variable because it deosnt seem to be relative
I do have a rotating object that rotates around the player where bullets are fired, should I call that transform instead?
Instead of basing the direction on input, base it on whether the attacker is on the left or the right of this object
aight ill give it a try
I'm trying to follow this tutorial https://youtu.be/fHPaG5C6P1M to do the localized text thing that uses a variable that changes depending on some code (in his example the variable is called holeNumber and he has the entry on runtimeUI.level which is a single entry but in my case I have multiple routines per day that switches depending on the time of day).
Each daily routine has a specific starting time and ending time. And in my Localization Table, each of these routines have their own key, compared to the tutorial guy he has only 1 key (Entry Name). So I'm kinda confused on how to make it work π€
Here's my method that's called everytime the daily routine changes but it doesn't work. For some hours it shows nothing (I guess empty string), and other days it tells me No translation found for 'New Entry' in DailyRoutines which is because I don't know what to name the key as I have multiple of them that I need to use on my UI depending on the current routine π¬ please
does anyone know why im getting this error message? InvalidOperationException: You are trying to read Input using the UnityEngine.Input class, but you have switched active Input handling to Input System package in Player Settings.
UnityEngine.Input.GetKey
the message says its coming from this here but it might be a unity setting problem maybe
unity 6 has input set to the new inputsystem by default. if you're using the old input system, configure that in the path mentioned in the error message
thx bro π
IEnumerator CalculateKnockback(int knockback, GameObject gameObject)
{
Rigidbody enemyRb = gameObject.GetComponent<Rigidbody>();
NavMeshAgent agent = gameObject.GetComponent<NavMeshAgent>();
agent.enabled = false;
Vector3 direction = gameObject.transform.position - playerController.gameObject.transform.position;
enemyRb.AddForce(direction * knockback, ForceMode.Impulse);
yield return new WaitForSeconds(0.2f);
enemyRb.angularVelocity = Vector3.zero;
agent.enabled = true;
}
could anyone help here? im trying to make the gameObject stop after AddForce to it
i disable the NavMeshAgent, add force then enable it again but the enemy is just sliding through the map
you're setting angularVelocity to 0. Angular Velocity is rotation
I think you meant to do linearVelocity
set it to linearVelocity, the enemy still goes sliding and gets stuck on the corner of the map
maybe i can add drag?
well it's going to continue until .2 seconds are up
IEnumerator CalculateKnockback(int knockback, GameObject gameObject)
{
Rigidbody enemyRb = gameObject.GetComponent<Rigidbody>();
NavMeshAgent agent = gameObject.GetComponent<NavMeshAgent>();
agent.enabled = false;
enemyRb.linearVelocity = Vector3.zero;
enemyRb.angularVelocity = Vector3.zero;
Vector3 direction = gameObject.transform.position - playerController.gameObject.transform.position;
enemyRb.AddForce(direction * knockback, ForceMode.Impulse);
yield return new WaitForSeconds(0.1f);
enemyRb.linearVelocity = Vector3.zero;
enemyRb.angularVelocity = Vector3.zero;
agent.enabled = true;
}
tried setting to .1f but dude is still sliding like there's no tomorrow
maybe show a video of what you mean?
Are you destroying the projectile immediately on the collison?
That would make the coroutine stop running before the end part can run
yeah try running the coroutine on a different object that doesn't get destroyed.
The video really helped it click for me that this is being started by a projectile that's getting destroyed
could have the one being hit do the knockback on itself
yea i might put the knockback on the enemy itself
because i got like 20 types of different bullets
this bullet is the only one doing knockback effect
yup that was the problem
working now
thanks!
Trying some gun recoil/knockback to my 2d side scrolling player, I want my cube to be forced back after firing the gun (which rotates about the character)
it currently works but its like jerky
when i fire in a direction the player moves like 2 inches to the left
almost teleports
is there something other than AddForce I can use?
use Impulse type for a 1 time force
where would I call it? In place of my force?
I get the ForceMode2D.Impulse
should I still use addfroce
timer -= timeBetweenFiring would be more accurate than timer = 0; just fyi
that's usually a sign of you having other code that overwrites the velocity every frame.
but lets say the TBF is 0.3f, and my timer is at like 3f, wouldnt a click just bring it down to 2.7f and do nothing
You would need to disable that code for the knockback period
the timer wouldn't get to 3f
it would get to 0.35f, and you'd do a knockback and reduce it to 0.05f
my move code calls rb.velocity in some parts would that do it?
yes
so how would I counteract that
disable that code during the knockback
just like call if !ApplyKnockback over the movement code
or switch to controlling everything with additive forces instead of overwriting velocity
possibly, with a bool, yes
you would need to have the knockback last a certain amount of time or something
also adding ForceMode2D.Impulse fixes the stuttering, but now it only moves up and down rather than in any direction
you would AddForce with Impulse type
that's because your other code is overwriting the x velocity, as I mentioned
wait how come I cant call my knockback script
its public
this is in my movement script
When you mouse over that it will tell you what the problem is
or if you look in your unity console
just says it isnt recognized
Then you don't have any class by that name
also how come my code isnt green
also no, it doesn't jsut say that. Error messages are more in detail than this
like the monobehaviour and whatnot
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
β’ :question: Other/None
but my other scripts work perfectly fine
did you put this script somewhere weird
hold up it might be not updated correctly
the GunKnockback script shows up as this
while my other ones are Assembly-CSharp
ill try to update yet again yay
is the file extension correct?
Good question and also is it in the Assets folder?
or is it somewhere weird
e.g. did you put it inside some package folder or something
no
its literally the same place I have eveyrthing else
not sure why it says miscellaneous its in the right place
when I try to create new scripts it says the same thing
do you have a compile error in the console?
Can you show some less cropped screenshots
not cropped at all would be ideal -e.g. with the project window visible in VS
no problem
then heres an actually working script
script editor is also updated I hope
trying to find my visual studio files rn
Ah your VS project window is hidden
wdym
yeah I was looking for that
aight I got it
the GunKnockback script is under Assets like all my other scripts
I really should organize them but rn they are all in the same Assets folder
oh hold on
GunKnockback does not show up as a C# script
like its there as a file
but not as an openable script
did you modify the .csproj file manually somehow?
might be a good idea to run the "Regenerate Project Files" under Preferences -> External Tools
i think you might be able to fix this with:
Edit -> Preferences -> External Tools -> Click "Regenerate Project Files"
damn, jinx
actually did that a few minutes ago, literally nothing happened
gonna try and duplicate a file that works directly from VS code to see if itll function
is this important at all?
the No supported VCS diff tools thing
Okay I somehow managed to fix things
not sure how or why but thanks fellas
okay now back to the actual reason why I am here
so after that's fixed is there still an error?
My guess was VS was just showing an error because the csproj was messed up and it didn't know about that file.
Unity was probably fine with the compilation
nope
honestly no clue why it messed up int he first place
there were no issues with the GunKnockback code or anything
anyways, trying to do this with a bool taht checks if im beingj knocked back or not
in the player movement
alright - seems reasonable enough. What's the issue?
you're setting isBeingKnockedBack = false every frame
oh wait thats in the update
you would need a coroutine or something here
to set it to false after some amount of time
or you could use a float timer
float timeOfLastKnockback;
float knockbackDuration = 0.5f;
public bool IsBeingKnockedback => (Time.time - timeOfLastKnockback) < knockbackDuration;```
and do timeOfLastKnockback = Time.time; when you do the knockback
for example
(quick and dirty example)
like so?
oh wait I tihnk that may have worked
hm no
almnost there, but the character slides for the duration of knockbackDuration which I mean makes sense
yes that's correct
So you could fix this in a few ways - one is rather than completely locking out the player controls, you do it gradually
two you can change the duration
definitely feels better when I make the duration shorter, although I still don't like being locked out of all controls
actually it aint too bad setting it to 0.1f
oh eyah thats perfect
thank you for your help
and for dealing with me lol
You can do Camera.main instead of that find by tag abomination
wait you use it later wtf
gottem
blindly copying it they don't realize its the same reference they could've used mainCam.ScreenTo
The update/start comments are still there so clearly a beginner π
hey if it works it works
we dont do that here
as a beginner its fine but later when you want to do things in a faster and more reliable way you will learn to abandon finding by tag/name.
so do I not need that line at all in my start script?
just copied it from my other script which controls the mouse rotation gun
From the screenshot it appears mainCam isnt used so yea it can go. Using Camera.main is best to get the main camera or using a Serialized field for other cameras.
is there any way to change the pitch of a PlayClipAtPoint method?
using it with my OnTrigger cuz I dont feel like using a coroutine and it seemed convenient
no
PlayAtClip is pretty limited
what you could/should probably do instead of this is just put one audio source on your camera and have it play everything with PlayOneShot
Iβve tried this before and the sound doesnβt fully play since it instantly gets destroyed
you could make it a singleton
I probably will just try a coroutine
Why would the camera get destroyed?
No so I attach the listener and stuff to the camera but itβs triggered by the OnTrigger on the bullet hit script
so? It's the camera now playing the sound
not the bullet
I said to put the audio source on the camera as well
But how would I make the camera play the sound when I need to call the sound to play when the bullet hits
Just reference the mainCam?
Like I said, make the script a singleton
Iβll try to
to make it easy
the bullet script just has to do like AudioManager.Instance.PlaySound(bulletHitClip);
time to learn
so when using relay for multiplayer, im having an issue where my a script running on my client is saying that IsOwner = false, and i was under the impression that if it was a script attached to their character, they were always owner.
Depends on your network topology
but if you're doing server-authoritative, I believe the server owns all NetworkObjects
Well im doing a host to client connection so im not sure what that would be considered, pretty sure the host is considered the server right?
Network topology is either distributed or client-server:
https://docs-multiplayer.unity3d.com/netcode/current/terms-concepts/network-topologies/
In a client-server topology, the server owns all NetworkObjects:
By default, Netcode for GameObjects assumes a client-server topology, in which the server owns all NetworkObjects (with some exceptions) and has ultimate authority over spawning and despawning.
https://docs-multiplayer.unity3d.com/netcode/current/basics/ownership/
much appreciated, ill take a look into those, seems like exactly what i need
Hi. I have a question regarding making npcs. Usually we use nav mesh agent. However, this comes with some issues. Firstly, the nav mesh agent default behavior is moving towards the goal direction and slowly turn until it reaches the right direction, therefore causing a "sliding" effect. What I want is the character to move in a more realistic way, only moving forward while turning to march the next waypoint. Ive gotten this to somehow work by merging a character controller and a nav mesh agent and disabling the agents movement and handling everything myself. This works ok on flat surfaces but on terrain or different heights it becomes buggy and desynced and stuff. Do u guys have an idea on how the proper way it's done?
That's not the solution.
What if I also wanna use root motion animation for movement
gotcha, my bad i misunderstood what u were asking
No worries.
I'd probably just check each update if they are looking at the direction, otherwise pause them from moving and correct the rotation
It's completely valid to use NavMeshAgents/NavMesh just for paths. How is it desyncing or being buggy?
There would be two colliders, one for nav mesh and one for character controller. For the most part they are synced and remain in the same place but sometimes I can see the nav mesh collider being completely out of place than the character controller capsule, even tho they're on the same object, and the nav mesh agent has update position to false.
I want them moving while turning so for example if they're facing the opposite direction they'd make an arch walking while rotating
Until they face the proper direction
I think I've managed to do something with rigidbodies with agents to get that angular drifting and dampening in a project, but I mostly just use a* project now and its custom controllers have quite a bit more features than what unity provides
a* is the algorithm, but a* project is a popular pathfinding library for unity
it's paid but has some features available for free
I would try the rigidbody idea though as I'm pretty sure you can manage something with that
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/AI.NavMeshAgent-velocity.html
Maybe just overriding the velocity would work fine too, either case there's usually a bit more logic involved if you want some custom behaviour with navagents because they are pretty basic
Are they separate objects? I don't think it should drift much if you have it all on the same object.
It is not. They're the same
hello, i need help with collision for my balls in a block breaker game, when my balls go very fast there is an issue with the balls (look at the video)
how i handle the collision :
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.transform.tag == "block")
{
Damage_block(collision.transform.GetComponent<block_sc>(), collision.GetContact(0).point);
}
else if (collision.transform.tag == "ground" && death_refusal <= 0)
{
Destroy_ball();
}
else if(collision.transform.tag == "ground" && death_refusal > 0)
{
death_refusal -= 1;
}
transform.up = Vector2.Reflect(transform.up, collision.GetContact(0).normal);
}
private void OnCollisionStay2D(Collision2D collision)
{
transform.up = Vector2.Reflect(transform.up, collision.GetContact(0).normal);
}
Show the inspector for the ball, especially the settings on the Rigidbody2D?
Anyone please ? π π #archived-code-general message
there's a lot going on here
first, it's not showing anything because of either the result for GetBinding is null, or it's not convertible to LocalizedString
the first step would be breaking that line into two and figuring out what is going on β add some more logs there
second, what do you mean you don't know what to name the keys? you can name them whatever you want as long as it makes sense to you and you're able to reference that later somehow
By that I mean as the tutorial shows an example with the main menu buttons text, each of those text have a unique key which is logical. In my case I don't have a unique key for my text as that text need to change everytime a new routine starts so I have to give it a new key each time (from those existing in the table).
I cameup with this solution and it works but it doesn't update the text to the new change of language until it updates the text on the next daily routine and as it's a string and not a LocalizedString, I can't subscribe to the StringChanged event that happens when the user changes the language (mid game for instance)
hi! i need help fixing this issue, ive looked everywhere and have no clue what has went wrong
you have an extra } I think
oh really?
configure your !ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
β’
Visual Studio (Installed via Unity Hub)
β’
Visual Studio (Installed manually)
β’
VS Code
β’
JetBrains Rider
β’ :question: Other/None
line 39
it makes it think that brace line 39 is to close the whole class making your method IsGrounded() outside of the class
that's why it complains
and your ide would tell you this if you configure it
so you want to update the text when the language changes?
you should be able to subscribe to some of kind of event in LocalizationSettings or something similar
maybe LocalizationSettings.OnSelectedLocaleChanged?
then you just execute the function that updates the text again
I need the text to update in 2 cases :
- When the player changes the game's language
- When a new daily routine happens (screenshot might help you understand what I mean by daily routine)
right, but what's your current issue then?
you need a function for updating the text, then this function should be called on both occasions: when the routine changes and when the language changes
I guess you already can detect when a routine changes, so that should be done already
to detect when the language changes you probably need to subscribe to an event in LocalizationSettings (I haven't used the package, so can't give you much more details there)
I had an error about null reference (I think it was the table) and it also said that it didn't find the key (each time).
I need to put my code back to what it was before so I can reproduce the error to give you more precision on the error π π
Here's the error, the text on my UI never changes to the new routine each time (It's written "Diner" all the time, after restarting again this time it says "Job", so I'm kinda confused even more)
how can i have a hook attribute for vars?
what do you mean? Like observing changes?
yea i wanna run a function everytime a field changes
Use a property and an event:
public event Action<float> OnHealthChanged;
private float _health;
public float Health {
get => _health;
set {
_health = value;
OnHealthChanged?.Invoke(value)l
}
}```
why is the event keyword needed?
It isn't but it's better coding practice. It means that only the class that owns the OnHealthChanged event can invoke it
Which is a good idea to enforce
Also means only the owning class can =, elsewhere its only += and -=
cool thnx guys
Basically makes it act like a publisher/subscriber model instead of just a regular delegate
Hey, I have something wrong with my logic making the text on my UI (and I guess the CurrentRoutine variable too) doesn't understand that from 23PM to 6AM, the routine should be Lights Out while in my case it stays at Night Roll Call up to 6 AM.
Because it doesn't realize 06:00 means the next day
it's checking if the current time is less than 06:00
when it's actually 23 hours or 1 day, and some minutes
so I shouldn't use TimeSpan for the comparison ?
mhhh, so what's the solution ? π€
maybe something like, if the endtime is less than the start time, add 24 hours to it
at least in the second half of the day
if you're in the first half of the day, subtract 24 hours from the start time if it's after the end time
somethign like that
I don't think you're right on this because time has 2 properties :
- Hours
- TotalHours
And as I'm using Hours, it goes from 0 to 23
I'm aware of what properties it has
if the current time is 23 hours
and you have a routine that goes from 22 hours to 6 hours
23 is not less than 6
but if you add 24 to it - so it's treated as 30
then 23 IS less then 30
23 IS between 22 and 30
so it will work
and, as I mentioned if it's 02:00
that's the first half of the day
so your routine that goes from 22 hours to 6 hours will be adjusted to -2 hours to 6 hours
and 02:00 IS between -2 and 6
So i think my logic will work just fine
so like:
TimeSpan startTime = task.StartTime;
TimeSpan endTIme = task.EndTime;
// Check if the task wraps around midnight
if (startTime > endTime) {
if (time.Hours < 12) {
startTime -= TimeSpan.FromHours(24);
}
else {
endTime += TimeSpan.FromHours(24);
}
}
// Then you do your normal logic here, using startTime and endTime isntead of task.StartTime/task.EndTime
But doesn't your solution seem like a glitch in the matrix ?
I have no idea what that means lol
Like it seems more like a patch on a wound than a real solution π
I disagree.
The real solution would be for your timestamps to all track which day they're on as well as just the time of day
but you don't want to do that, and you'd have to write a ton of really complicateed code to generate those timestamps from the local times all the time
another point would be that your timestamp should probably say 30:00 instead of 06:00 to really indicate it's meant to be on the next day
but they do π€
Like it has all of these properties making it if you want just the time of the day you can get it , if you want which day it is it has it too, if you want the total hours it has it, so it has everything
bit more messy but seems easiest would be to just have 24 hours and for each hour you select the task
But it's more painful and I want to avoid that π₯²
Not a solution but just a question/thought when reading this as I haven't implemented something like this before. In some situations would it be maybe reasonable just to treat any time of day scoped task/code in a 3 day/72 hour context all the time instead of mostly 24 but sometimes more than that (72 because all of yesterday, all of day, all of tomorrow). and then you could restrict or display that info conditionally based on if it overlaps or not?
yeah but you're not creating them as such
you just wrote 06:00
so you're treating it as a "time of day"
rather than an absolute calendar time
when you put end time 06:00 on the last task it doesnt magically know u mean the next day
yes it has the capability for that but...
doesn't mean whack if you don't tell it such
true but thats because I can't use an absolute calendar time as each day passing the routines are the at the same time of day π¬
so yeah I think the 24 hours solution you gave is THE solution π
can't you just put it ends on 24:00, then at the start of the day put lights out from 00:00 until 6
and just skip changing stuff if the next task is the same as current task
I want to avoid that to keep the SO routines clean π
don't see what's unclean about that
this also means you can switch routines
with your current how tf do u handle changing routines
exactly, so it's convenient to make your code understand the "next day" and "previous" day logic with some kind of heuristic like I wrote
if for example u wanted to like put the dude in solitary or something
or different routines for different days would be easier
instead of handling some edge case where people need to get up sooner or later but the lights out is hard set as until 6 am from the previous day
what do you mean "how do I handle changing routines" ? π€
well i mean its not especially hard but if you did it that way instead you wouldn't need any special logic at all
actually to be honest why do you need an end time at all?
why not just have start times only for everything
you can infer the end time by looking at the start time of the next task
it may be they're entering a zone at a given time and at any given time that zone may have a certain event happening or no event at all
so the question, when entering the zone, is "what is the current task happening now"
That's my understanding
at first I had an end time because "FreeTime" wasn't part of the routines as it's not really a routine that needs some checks to see if prisoners are in a specific area, but yeah right now I think I don't need it anmore
you could do it with putting free times in yeah
yeah that's already the case now
would that solve the issue with 10 PM to 6AM ? or do I still need your solution for that ? π€
Crossing a day boundary, you should be able to detect that or define it so both 22:00-23:59 and 00:00-06:00 can be true.
how ?
If we get the total length of the event and then do start + duration, we can see if it goes past the day end (in whatever units you use).
Then you can perhaps change the end time used to be day end?
wouldn't that mess the Days property ? Because I need it to be accurate as I will also display it on my UI to let the player know what days he's in π
I don't really understand your current way of checking the event but using the lowest unit like seconds or milli seconds is easier.
why would I do that with seconds or milliseconds while my routines SO use whole number representing the "Hours" ? π€
If you track the day the player is in since starting the whole game then just work with time relative to that
All time can be second or ms since then and you can get the start and end time for events from that and work with this easier
No since, the time starts since he started the game itself, so not including the main menu and pause menu and stuff
And I think at some point I wll need to pause the routine system for a minigame break (around like 6 PM) but I'm still thinking about that
I mean your gameplay time and days not real time
If you pause that advancing when paused then you track it somewhere yes?
I didn't write that part of the code yet but everything related to time is done here in my SO_dailyTasks.cs SO