#archived-code-general
1 messages ยท Page 57 of 1
Yeah, well it's the only option for me...
Are you a student?
Yes
I could use Rider...
but I don't know it...
Is that the "preferred" IDE for Unity devs on Linux?
It's the preferred IDE on every platform if you can get it
VS Code is the least supported one
They're not supporting VS Code's debugger plugin, and they don't even add the VS Code package to new Unity projects any more
I pay for Rider, it's very good. When the EAP is running you can also use that for free.
The cost goes down over the course of 3 years
I mean yeah, JetBrains IDE's are good... but I don't have the money to pay 149โฌ for it as a hobby
If you don't want to go through the student stuff right now the EAP is currently running so you can just download that https://www.jetbrains.com/rider/nextversion/
is VS fine (not code)
Rider should feel very familiar then! Otherwise, you'd probably get more out of asking about VS Code on the forums
VS is completely supported
89โฌ is better... but still quite expensive for a hobby
idk I never used it
:)
ehhhhhhhhh there are a lot of hobbies where you spend a LOT more but thats kinda unrelated lol
Hmm... true
Also should note that former student license holders get 40% off so you wouldn't be paying that 149โฌ for the first year, but anyway I'm sure you can figure it out, maybe when you're no longer a student Unity will have updated to .NET 7-8 and VS Code will become supported again
:o 40% off sounds nice
I don't think I'd be switching back to VS Code when I already did a lot in Rider
ยฏ_(ใ)_/ยฏ
is there a way to put my custom enum List as argument in PhotonView.RPC using pun2?
Might be better to ask in #archived-networking
ok
Ooohhhh.. thanks Rider ig... that is cool ngl
How can I change an input joystick axis from being from -1 to 1, to 0 to 1?
Basically, -1 = 0, -0.5=0.25, etcโฆ
(x + 1) * 0.5
Is it possible to use Animationcurves in the Unity UI System or do we have to make or own splines?
Everything is possible.
Kinda depends what you mean by "use" here
use them to do what
I mean like a slider or button, just drop in an animationcurve so players can for example tweak a curve to determine spawn behavior in the build.
public AnimationCurve myCurve; works out of the box.
Yeah but thats inspector only, isnt it? What I mean is instead of this here:
I want something like this here I did for the level nodes:
I mean it is programmable but maybe unity has some ready to use Unity.Ui - Animationcurves where I just have to swap textures or something like that
This is a spline, not an animation curve
I don't know exactly what I'm looking at here TBH
or what it has to do with curves/animation curves
nvm
Unity has a Spline package, if you're interested in splines.
isnt code i dont think but anyone know what the error
assertion failed on expression : 'Get SystemInterested(transform, system) != enable' means, 4 of em pop up after I end my play scene
seems kind of #archived-dots related? ๐ค
Could be that you have something in If Unity Editor like a variable
Does anyone have an idea about this? Other inputs work fine, and it works on windows, but just not on linux its very weird
I dont think its input settings? And im not sure what physics settings would make it not work on linux
Ok SO rays are getting cast at the correct position
between linux and editor in windows, the ray coordinates can be the same
but the item will only pick up on one system
hmmmmmmmmmmm, so i would assume its a physics problem between target systems
but why would it be different?
Did you try to use a public layermask inspector value instead of your bitshifting 1 << 8 thing? Just to be sure there is no difference on both OS
whoops meant to reply
I can not get my binary formatter save to work for the life of me
https://codeshare.io/mpbzLX https://codeshare.io/qPm8Ax Can someone look at my code and see if they can figure out whats wrong with it?
That's a good thing, you should not be using BinaryFormatter at all
why?
It's dangerous for your users
what should I use instead then?
the article mentions some alternatives. You can also use well known JSON serilializers like Unity's JsonUtility etc...
maybe it will work if I just switch the serializer to that then, because I couldn't find the issue with my code for the life of me other then the data just not coming through correctly
Well I mean in your test you're not even saving the data at any point
?
// test save and load methods with test note data
public static void test()
{
note[] notes = new note[3];
notes[0] = new note(1, true, 10, "note", "turnRight");
notes[1] = new note(2, true, 25, "note", "turnRight");
notes[2] = new note(3, false, 40, "note", "turnRight");
foreach (note note in notes)
Debug.Log(note.ToString());
saveLevel("test", notes);
note[] notes2 = loadLevel("test");
foreach (note note in notes2)
Debug.Log(note.ToString());
}
oh I missed it somehow lol
lol
you should be using using statements btw
whenever dealing with things like FileStream
what does that do?
there's a risk you are not closing your streams properly
it ensures streams are opened and closed properly.
I see there's resizable window, but yeah, shame. Thought there'd be more
so in my case, I would use the using keyword like: using (stream) { LevelData data = formatter.Deserialize(stream) as LevelData; } ?
then I also don't have to close it after right?
Or just use File.WriteAllText / File.WriteAllBytes and skip all the stream stuff
I like the streams lol
Now I just have to figure out how to change my code to use JSON serializer
also, JSON stands for java script object notation, but I can use it in c#?
Yes
It's just a text format used to represent data. Not really a language or anything
No idea if this is the right place for it. My player character is animated so his sprint is slower at the start, but full speed during the loop. The animations have no root motion. I'm assuming this is a code thing though, I need to figure out how to change the player character's speed so he's slightly slower at the start of the sprint with a pause before going full speed.
Had a look around online and couldn't quite find any info on what I'm trying to do, so there might be a term for it that I'm not aware of.
Animation Curve for movespeed
Genius, that didn't come to mind at all. Thank you!
if I save a json file to a folder using write all text with the same name as a json file already there, will it overwrite the old file?
You could test it
that's probably what I'll do
https://codeshare.io/MNE0Je https://codeshare.io/EBEKJo I am having the weirdest issue with my constructor in these classes
nvm I am dumb
What would be a good way to figure out all of the objects that are visible from a certain point in my scene? I considered raycasts, but figured that that would be bad for performance, and it would be very precise for scenarios where the center isn't visible, but the edges are.
bad performance?
I don't know if that's accurate, I just figured that doing a raycast for every object in the scene is a bad idea.
https://docs.unity3d.com/ScriptReference/Renderer-isVisible.html as long as your point is a camera that is
nothing wrong with a bunch of raycast, the engine can handle a decent amount just fine
It's not gonna be precise either. How do you know what to raycast against if not the center of the objects?
Unless you raycast per pixel on the screen, which is really gonna kill the performance.
I'd use what DROD mentioned or maybe iterate all the objects and do some math involving their bounding boxes, view point and frustum angle.
There might be a utility method to make it easier. That would still be pretty heavy depending on the number of objects...
Yeah, that's kinda why I was hoping that there's a better method. The renderer.isVisible thing I don't think would work very well because it's not a camera, and if I'm reading correctly, that returns true if it's visible by any camera.
What's the purpose of doing that though? Maybe there's a better solution?
Well you could put a camera there that only renders a certain layer. @inner yarrow
Duplicate the object your trying to detect as a child, put it on that layer and check its renderer etc
I want this because I have to duplicate part of my scene, but I only need to duplicate the object's that are visible from a certain point.
That would kinda involve some unneeded camera overhead(like rendering these objects)
Asking about your attempted solution rather than your actual problem
Barely, if theyre only rendering one layer.
Maybe GeometryUtility.TestPlanesAABB the relevant objects?
I'm not actually asking about my solution. My problem is needing to know which objects are visible from a point, and that's what I asked.
Yeah, I guess I could try that.
not really specific enough to its purpose
is it a camera effect only ? or something
yo guys anyone know how to add a timer until the next line of code is activated?
Like for benchmarks? Stopwatch?
like a stopwatch
@inner yarrow this def
ok, I'll give that a try.
No, Im suggesting Stopwatch class lol
im trying to have it so when a game object colides with another it waits for a moment then will change color
oh XP
Ah nope not Stopwatch
oh
You probably want to look into coroutines
ok ill read the doc and pull up a few vids, Thanks for pushing me in the right direction :>
Or raise some flag and wait in update.
Hello I'm setting up a bunch of raycasts for hit detection in a melee game, I need to be able to set these points manually and I was wondering if its possible to create these positions through the inspector instead of adding empty gameobjects to each weapon to use as points. I tried using a list of vector3's but there's no visual for the placement of these points
You can add visuals using Gizmos and Handles
quick question: can you change the outer spot angle of a Light 2D in script?
ya probably
every component is a script
so probably
oh lmao ty i didnt realize point light and spot light referred to the same thing
appreciate it
Yeah I think in 2D point lights also become spot lights with that thing
my OnCollisonEnter is bugging out it keeps saying its wrong but every other script reference looks like this plz help
it keeps saying its wrong
Wdym? Are you getting an error? What is your full error message?
opps sorry here:
you have a yield return statement in OnCollisionEnter
You can only have yield return in iterator methods, which this is not one.
oh
an iterator method must have IEnumerator as the return type, not void
welp back to the drawing board i suoppose
oh
OnCollisionEnter can be a coroutine
ok
Ok, I am really confused. I am trying to get a Raycast to work on both windows and linux. For some reason, my item pick up script works on windows, and in the windows editor but NOT on Linux.
This is the code for detecting a raycast. On linux, I get the print for "Pickup Press", and the print for "Ray Created" but not the "Ray Hit an Object". On windows, the "Ray Created" Coords MATCH the linux ones in my test case, but the linux one doesnt get the raycast to hit the item.... its really weird
public void Pickup_Pressed(InputAction.CallbackContext ctx)
{
Debug.Log($"Pickup Press: {ctx.performed}");
if (!ctx.performed)
return;
RaycastHit hit;
Ray ray = main_camera.ScreenPointToRay(Input.mousePosition);
Debug.Log($"Ray Created: {ray.GetPoint(0f)}");
if (Physics.Raycast(ray, out hit, inventory_grab_range, mask)) // Do a Raycast with only layer 8 (Items)
{
Debug.Log($"Ray Hit An Object: {hit.transform.gameObject.name}");
Transform hit_transform = hit.transform;
GrabItem(hit_transform.gameObject);
}
}
are these objects moving around quickly or recently before this code runs?
that doesn't really answer the question ๐ Kinematic objects can move via script
ok well they are not moving
Is anything messing with Time.timeScale or Time.fixedDeltaTime or Physics.autoSimulate ?
- No, 2) uhhh No, 3) i dont think ive ever seen that
would it only be in my own codebase?
i can do a search through my IDE
It's possible for plugins/assets to change these things
but not likely. Worth looking though
I know for example Obi Rope messes with autoSimulate for example
Well this is interesting...
My editor has crashed out of nowhere after putting the same object in both the Viewport and Content section of a Scroll Rect. It seems to crash every time I open the specific scene where I did this...
[C:\build\output\unity\unity\Runtime\BaseClasses\PPtr.h line 271]
=================================================================
Native Crash Reporting
=================================================================
Got a UNKNOWN while executing native code. This usually indicates
a fatal error in the mono runtime or one of the native libraries
used by your application.
=================================================================
=================================================================
Managed Stacktrace:
=================================================================
at <unknown> <0xffffffff>
at UnityEditor.AssetDatabase:OpenAsset <0x000f6>
at UnityEditor.AssetDatabase:OpenAsset <0x0009a>
at UnityEditor.AssetDatabase:OpenAsset <0x00092>
at UnityEditor.ProjectBrowser:OpenAssetSelection <0x001aa>
at <>c:<.cctor>b__1_2 <0x0009a>
at UnityEngine.GUIUtility:ProcessEvent <0x00114>
at <Module>:runtime_invoke_void_int_intptr_intptr& <0x001b5>
=================================================================
Received signal SIGSEGV
Obtained 2 stack frames
RtlLookupFunctionEntry returned NULL function. Aborting stack walk.
<Missing stacktrace information>
(btw I shortened the stacktrace bottom up to fit inside the Discord character limit)
submit bug report to Unity if you can reproduce it
Already done, mainly was hoping someone had an idea here ๐
in my codebase nothing is changing those
Thing is...this happens all the way from 2020 to 2023 alpha 2
can you reproduce it though? if you do that again in another scene does it die again
Imean there's not much to go on from the stack trace. That's about as generic as a segfault gets.
I can try to yeah
Unity will be able to reproduce it with debugging symbols and figure out where in their own native C++ source code it actually happens
without that it's shrug city
One thing to note, if I force it to load a different scene, it doesn't crash
wdym by that
Yeah I thought so
literally going in the configs and changing the last loaded scene
@leaden ice anything else that would kill it? and something that would ONLY happen on linux?
specifically ubuntu
if that matters
I'm noting that you're doing Input.mousePosition even though you're using the new input system. Shouldn't you do Mouse.current.position.ReadValue() instead?
maybe the "both" input mode doesn't work on Ubuntu
that WOULD probably be a good idea
yeah
maybe
i just used the old one because i new the magic trick for it and it still worked
so why change it lol
this could be a why ๐
but it IS showing the coords of the raycast correctly
so i doubt thats the issue
would still be good to change for compatibility
oh is it? My thinking was maybe mousePosition was returning 0, 0, 0
yeah no its returning the correct value for the ray position
ray.GetPoint(0f) is just the origin of the ray
which will always be the same
no matter what mouse position you plugged in
it's just the camera's position
I think it could be the mouse thing still
ohh nvm i get it now im just bad at thinking
yeah
i have 0 braincells and i should quit gamedev ๐ ๐ ๐ ๐
jk
try it and lmk
i dont wanna try quitting gamdev!!!!
BTW
how can i replace Input.GetAxisRaw("Mouse Y")
and the other one
with new input system so i never use both anymore
Mouse.current.delta.ReadValue().y
thank you
i can also just shorten it Vector2 mouse_delta = Mouse.current.delta.ReadValue();
very nice
only downside is it goes HYPERSPEED compared to the old one
very weird
i will just apply a fixed multiplier ig for now
Not really sure if I have it the same way I did before but it hasn't crashed so 
All I can go off of is that it happened after I put the same object in both the viewport and content section of the Scroll Rect, it happens no matter the unity version, and it crashes every time I open the scene
I looked at the scene inside a text editor and it looks fine so I doubt the scene itself is corrupted
hmm you're not multiplying by deltaTime right? I think I've heard of this before... people saying they get different scaling on the new mouse input ๐ค
i dont see it but i AM skimming
so
void mouse_look()
{
Vector2 mouse_delta = Mouse.current.delta.ReadValue();
Vector2 raw_frame_velocity = Vector2.Scale(mouse_delta, Vector2.one * menu_handler.look_sensitivity * player_camera_control_adjustment);
frame_velocity = Vector2.Lerp(frame_velocity, raw_frame_velocity, 1 / smoothing);
flash_frame_velocity = Vector2.Lerp(flash_frame_velocity, raw_frame_velocity, 1 / flashlight_smoothing);
look_velocity += frame_velocity;
flash_look_velocity += flash_frame_velocity;
look_velocity.y = Mathf.Clamp(look_velocity.y, -90, 90);
flash_look_velocity.y = Mathf.Clamp(flash_look_velocity.y, -90, 90);
player_transform.rotation = Quaternion.AngleAxis(look_velocity.x, Vector3.up);
camera_transform.rotation = Quaternion.AngleAxis(look_velocity.x, Vector3.up) * Quaternion.AngleAxis(-look_velocity.y, Vector3.right);
flashlight_controller.Move_Flashlight(Quaternion.AngleAxis(flash_look_velocity.x, Vector3.up) * Quaternion.AngleAxis(flash_look_velocity.y, Vector3.right));
}
discord be like
"what is text formatting?"
!code
๐ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
EditorWindow - What is called when I move/create a new window?
still
ehh you're doing all kinds of like... mouse look acceleration in this code
hard to judge what's up
fair enough
but tested on a lower framerate system (the linux system that wont raycast correctly djfsklfjasf) and it didnt scale weirdly after my multiplier
so i think we are good
anyways
raycast issue still stands
this is weird
im gonna try setting some sort of reference point maybe and picking a point a few units down the ray
really? Could've sworn that'd be it
maybe that would provide insight
yeah
no clue
its real weird
i just turned off both mode as part of the next update im gonna try
any other suggestions
it takes a few mins to update so i dont wanna update without some bigger change
nothing I can think of
maybe add more logging
like logging mouse positions, the ray definition itself, the layermask value, inventory_grab_range, main_camera etc..
just dump a whole bunch of info and see what's different if anything
inventory_grab_range is a const
its 5f
main_camera is set in Awake() using Camera.main
but again the ray coords are teh same
so its 99% sure the main camear
It's theoretically possible for this to return a different thing, especially if you have multiple Main Cameras in the scene by accident
none of my other cams have main cam but i can try
and in a less likely scenario - you mess with camera tags during initialization
i think ive used tags once
or maybe you instantiate the main camera?
no
Could be an order of execution issue if the main cam is instantiated
main cam is in the scene, and has a script that moves it to the client-owned player object when the scene starts
not other player objects
that would be broken
lol
hmmm ok so
networking is involved?
That's definitely a monkey wrench
yeah
i feel like it wouldnt affect it too much though?
idk
also there are weird cases where you CAN pick up items
but i havent found anything consistent yet
so realllllly not sure
Networking affects everything ๐ฌ
Looks like you've got a broken scene file
but like its a raycast and you are the host and it works on two seperate machines and the editor, both as client and as host
and on linux it does not work as host OR as client
but idk maybe linux networking hates netcode
yeeeup
Time to figure out what to do about this ๐ฅฒ
do you use version control?
Not for this project
Company security standards 
oh btw almost every networking framework absolutely messes with Physics.autoSimulate which I was mentioning before.
Which networking framework are you using?
netcode
that might do it
but
why on linux
and not windows or other windows or editor windows
objectReference: {fileID: 2077924899, guid: 00000000000000000000000000000000, type: 0}

also what do you mean earlier by the actual definition of the ray?
basically just printing out the ray
{ray} ?
you can call multiple casts on the same ray right?
i wanna try a mock cast for debugging that doesnt have item restriction
like flag mask i meant
yeah i mean just printing the actual ray itself
Kind of a weird "hail mary" shot here. What happens if you run Physics.SyncTransforms(); right before the raycast
uhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh
it just works tho
but like
only sometimes
the raycast hit an item, and when i went to try those coords from the log
it worked on the windows version
so the coords and dir are correct
im confused lol
ok so it only hits my items on very specific areas in linux
will you be here tommorow i wanna go sleep rn
and also when the ray DOES hit, it just picks up the item as expected
so its something with the ray not hitting for some reason
alright then
pain\
i dont wanna wait another 6 mins before sleep so gn
Hi I was wondering if someone could help me,
So basically I'm trying to setup a custom editor window, to automatically select an object from my project folder to show up in the inspector, basically what normally happens if you select it normally with the mouse but I just wanted to tie it to button click, is there anyway to do that?
Quite hard to google this since you type in something along the lines of selection and inspector, and you get specifically editor related setup, Selection.gameObjects (which only works for objects in the scene not project folders).
Any help would be appreciated, thanks!
So this works, it didn't work for me the first time around (and also the documentation saying the object selection in the scene is misleading) because I didn't setup the path correctly but basically in order to select something from a specific folder, you'd do
UnityEngine.Object objectYouWantToSelect= AssetDatabase.LoadAssetAtPath("Assets/Project/Folder/ObjectInFolder.asset", typeof(UnityEngine.Object));
Selection.activeObject = objectYouWantToSelect;
and that does the trick!
okay sorry a bit more work than what I thought, but basically this is what I found https://forum.unity.com/threads/selecting-a-folder-in-the-project-via-button-in-editor-window.355357/ , I have to use the selection bit and then the ping object method call, couple of steps in between but overall it's pretty simple to setup
nice, thanks for sharing!
yup no problem! I setup a way to load scenes from a window, since you know it's annoying to have to shuffle through and find your scene, so what something else but for specific scriptable objects, the cool thing is having a button that auto generates the code for the buttons (good ol' automation) so once I figure out the kinks to selecting an object, it's gonna be updatable with the click of a button ๐ it's pretty cool having code generate code
Hello, just wondering if there is a neater way to do something like this? It stores all the different positions my blocks can go in for each level. I was thinking SO? Although it will probably be a pain to enter each of the positions into it.
A list
I agree with that, but it depends on your use case a bit, and how you structured your levels
You could've made a scriptable object containing a list of vector3s, so that each level would have its own scriptable object
But it kinda makes me wonder why you wouldn't just use different scenes at that point
Those y values looking pretty precise
The position on y and z seem pretty equal, arent they? Is there any pattern that you could follow to turn this into code or at least calculate for each level on base of some empty transform clamping the max and min values? Just wondering what will happen when you go beyond level 3
Thanks all for the feedback I did feel this was messy when putting it together.
I think some form a list and calculation to determine the values would work well, I hadn't realised how similar they work so I think I might be to create a loop to generate them instead.
'level' was probably a bad word to use - it's more of a wave, Once all three waves have been completed the next level (scene) loads.
SO is only useful here if there is more logic to it
Even then, this is hardcoded, and a SO is more for configurable data
A list is the right answer here
Just to add, you could still combine SOs for the "level" with lists for the "waves", if he really needs to set it up manually
hey guys! i have an 'invincibility' method for the player. so if the player collides with the enemy then they have 4 seconds of invincibility within which the enemy cannot attack the player. however, that does not seem to be working. i have attached my code for the invincibility method.
It'd be best to have a bool for the player saying they're protected and checking on damage if they are
@thin aurora @plucky inlet Cool that makes sense, I'll keep that in mind going forward I think a list might work once I get the loop figuring out to generate the values. I do like the idea of using using an SO to hold the lists for each levels if they do need to be hardcoded.
Hihi, so I have multiple player characters that all have different attributes such as stats. I have all the stats that a character would have as a scriptable objects. I'm currently trying to figure out how I would differentiate script-wise between the characters. Would it be with inheritance or is there another way? If I have characters inheriting from a base character script, how is that any different from not using scriptable objects?
First question, do you use one scriptableobject per character?
Yes
then you already have a separation for each character, dont you? Where are you stack exactly?
If I had three characters, and in the scripts it takes the stats and does whatever, do I just need the script copy pasted three times?
You need 3 scriptable objects
I do
You only need 1 script
Exactly, you just use one script on all players but they take in different SOs as a parameter. Like GameObject A,B,C all hold the "Player"Script but with different ScriptableObjects attached to them.
Hmm that was how I had it. I just wasnt sure if that was going to cause issues
maybe post the issue you had instead
As long as you do not share any other static values between those scripts. But again, it depends on your setup. If you add fancy systems to it, it will surely cause issues you can solve. thats dev life ๐
I didn't really have an issue
I just didn't know if there was another way to do it
okay thank you !
ty ๐
there is many ways to do many things, but SO is a good modular way to do it
Usually there are always multiple ways for one solution, but it always depends on the situation. Just test around, come here if you want help or suggestions, prototype system ideas and so on ๐
But I wont be tired to tell, if you use scriptbale objects, they will NOT persist their updated values in runtime. So if you think, your ScriptableObject is an easy way to save player stats over multiple runtimes, it wont. you have to store the scriptable objects state when you leave the game and overwrite it when starting the game. Just one thing to be sure about in SO handling
Good tell, I don't think the way I want to use the SOs involves changing their values but instead getting something from their values and changing that
like uhh
A stat such as constitution, it converts into health and instead of messing with the stat itself I just mess with the health
Just wanted to warn you, cause I learned it the hard way back then ๐
I will keep that in my mind
hehe use props!
I try not to make anything in SO public without it
[SerializeField] private int moveSpeed; public int MoveSpeed => moveSpeed;
Not sure what you mean. It still will not save the values if you restart runtime, or dont I understand what you mean ๐
Oh I meant so you don't accidentally change the SO values no? if they are public you might
I misunderstood what you said here, thought you meant you accidentally changed your SO values lol
Ah no, I was talking about, lets say, you load your player SO and you change its experience value from 0 to 20. If you restart the game in runtime, it will revert to 0, even if in Unity the values will stay at 20. ๐ But good point on your props tho about not accidentally changing them ๐
ah ok ! yeah def seen some strange YT vids talking about using SO as saves, big no no
so yeah good tip you gave there for that one!
I mean I use it to save stuff in combination with a simple File being saved and loaded, but as you said, not solely on base of the SO system ๐
So if I wanted to change the stats on the SO I'd want to use something else?
Like if they level up or something of that sort?
yeah, you basically just use the SO as a default structure. the data going in and out should be something updated in runtime and saved locally somewhere, so it can be your overwrite for your default SO state
You can have different SOs per level if you wish, but ultimately they should only serve as a base template of the stats
Hey, I'm working on adding 3d object preview in UI through RenderTexture, so I have to position camera and object in the world. Are there any good practices of doing that? And if I'll need to render multiple objects with multiple cameras at the same time, how should I position them?
So what would be the alternative?
A default class that you override with a database for example. The ScriptableObject system is useful for making pre defined things like classes, enemies, levels, items and so on. If you want to update those, you always have to detach the updated data from it. But that goes for a default class too. Detach it to a database, a file, a json whatever
Honestly, it's probably fine to just put all the stat levels in the SOs. Maybe have a list of SOs, and you'd read each one accordingly everytime you level.
Or, a single SO per hero with a list of stats they have at each of their levels.
But that way you would limit yourself to predefined values. If thats what he wants, sure can work then
No I don't want anything predefined
Yeah, if you're starting out, which they are, I think that's preferable.
That's fair but the alternative doesn't sound that much harder and I would rather not dumb anything down if I don't have to
Once you get the hang of serializing your data from and to then it's less of a problem.
I feel like I'm being stupid.
With the new input system (Using Unity events e.g callbacks).
How in the world do I figure out if the player is holding a key..
Did you check the docs about the callbacks you can hook into? Like performed, IsPressed() and so on?
I have but I'm also tired so that's what I said I feel like I'm being stupid
I'm looking at the interaction part of the docs rn but I can't find the function for Hold interaction 
If you are tired, you might just wanna take a break?
Ty that worked.
I'm working on a swimming system
I was being stubborn and was trying to do it in the callback system
Hi!
Does anyone know how to play a sound when you interact with an NPC? I've set up an Box Collider next to them and a Sound, but I am struggling to find a script/code when key "E" is pressed that they play a sound saying ex "Hello!". Anyone know how to code it?
#๐ฑ๏ธโinput-system for how to get the E key and https://docs.unity3d.com/ScriptReference/AudioSource.html on how to play audio
Ty mate, but i can't see any inputs in the code when u press anything to trigger the sound. I want the sound to play inside the box. Is there another script for that?
there is no PlaySoundWhenPressingAKey(Key, Sound); function. you gotta hook it together yourself. thats why I suggested you to talk in input-system to learn about how to actually call a fucntion with the button press AND look at the audiosource component to know how to call an audioclip. combined with a script of OnCollisionStay should get you going
Hello, I want to save my data on to a database, i haven't picked the data base because I dont know which database will be the one I need, I need my database to be able to do this:
- assume that you have 50 players and you want to save each of their names, scores and Profile pictures...
I want a database that saves even the profile pictures.... can anyone help me by telling me which database i need to use?
do you want to save them online on a server or just locally?
I want to save them locally or on a free platform you know like firebase
the important part if I keep them locally is to also keep the pictures
How would you get the pictures?
browse for them
and of course if there's a saved database, load them in the beginning
you can just use a simple file with json in it and the path to a downloaded image to do that, if you dont really work more with a database then just saving a list of players with images
here is the crux of the problem, do those data bases save the sprites... because those pictures aren't stored on the web... I want that if I move that database to another computer and run the app... the pictures will be loaded... I have thought about writing Json files... but no... I need to save the sprites themselves
if you need to save an image, use base64 if you really need to
thank you.. and yes I do need to... I wont be synching those pictures in an online game
any other databases that can save pictures?
a database is just a structure of text, those images in a database are also just text in the form of an URL to the file.
so you would have to use string values to create those images, which would be base64 strings
so I need to save the pictures in the resources folder for example? @plucky inlet and the database will load them right?
you know what... i will do it the old fashioned way
you would save them to the persistentDataPath of your app on runtime and load them from there
yeah that's what I am thinking
How would I go about making a save system for my game? It auto saves every X minutes and can be manually saved. and when you open the game and hit play, it loads the last saved level at the last saved position.
I think there's a video for brackeyes on save systems... you just have to trigger it in update every 5 secs
What exactly are you struggling with?
I have no idea how to save or load progress.
Saving progress is basically saving values that represent the progress. thats something you should think about tho. So, for example. position of the player, experience of the player, inventory of the player. maybe enemy states and so on. Only you and your game know
Ok thanks!
how about just telling the problem
sorry i was recording the problem
so i have this script:
if(Input.GetMouseButton(0))
{
if(PlayerStats.movingObject != null)
{
print("testing1");
Ray ray = cam.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
Physics.Raycast(ray, out hit, Mathf.Infinity, LayerMask.NameToLayer("Terrain"));
print("testing");
PlayerStats.movingObject.transform.position = new Vector3(hit.point.x, 0.1f, hit.point.z);
}
}
when i move, its kinda buggy
why?
im so confused
"buggy" = ?
how do you set the moving object?
If(Input.GetMouseButtonDown(0))
that is getting the mouse button... not setting the moving object
how do you set ```cs
PlayerStats.movingObject != null
oh
Wait lemme show u
The whole code
Vector3 mousePosition = Input.mousePosition;
mousePosition.z = 10f;
mousePosition = cam.ScreenToWorldPoint(mousePosition);
Debug.DrawRay(transform.position, mousePosition - transform.position, Color.cyan);
if(Input.GetMouseButtonDown(0))
{
Ray ray = cam.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if(Physics.Raycast(ray, out hit, 100))
{
if (PlayerStats.movingObject != null)
{
PlayerStats.movingObject.transform.Find("Movement").gameObject.SetActive(false);
PlayerStats.movingObject = null;
}
if (hit.transform.GetComponent<BuildingInfo>())
{
hit.transform.Find("Movement").gameObject.SetActive(true);
PlayerStats.movingObject = hit.transform.gameObject;
}
/*Debug.Log(hit.transform.name);*/
}
}
if(Input.GetMouseButton(0))
{
if(PlayerStats.movingObject != null)
{
print("testing1");
Ray ray = cam.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
Physics.Raycast(ray, out hit, Mathf.Infinity, LayerMask.NameToLayer("Terrain"));
print("testing");
PlayerStats.movingObject.transform.position = new Vector3(hit.point.x, 0.1f, hit.point.z);
}
}
if(Input.GetMouseButtonUp(0))
{
if (PlayerStats.movingObject != null)
{
PlayerStats.movingObject.transform.Find("Movement").gameObject.SetActive(false);
PlayerStats.movingObject = null;
}
}
Here is it
The code
So if you move your mouse to fast, you will lose the hit on your target and it wills et it to null and not move it. As I expected, you should hook the setting null of your movingobject to a mouse button up handler or something to release the instance you are trying to move instead of raycasting while you move it
But its inside the onMosueButtonDown
Pool object classes and unityengine.pool has been added since 2021?
Hey, I want to rotate a transform around the y axis slowly and with a limit. My current setup for that is something I threw together to "just work" but I need to phase it out now
if (Mathf.Abs(axisFront.transform.localEulerAngles.y) + 3f < 60 || Mathf.Abs(axisFront.transform.localEulerAngles.y) > 360 - 60 -3f) {
axisFront.transform.rotation = Quaternion.AngleAxis(3f * -agentController.moveAxis.x, axisFront.up) * axisFront.transform.rotation;
axisBack.transform.rotation = Quaternion.AngleAxis(3f * agentController.moveAxis.x, axisBack.up) * axisBack.transform.rotation;
}
What is the proper way to do this ? Its been ages ive used unity
Does that mean if i dont stop holding mouse
The object will forever in Playerstats
Oh yea, the raycast function in getmousebutton use to be a if condition. And the print is inside the if statement body, and the testing1 was printed but the testing was not
Hey im having problem making coins in my game. And how do i store the number of coins even if the game is closed so when the player is bback on the bnumber of coins collected should be the same as the number of coins collected before closing the game
<@&502884371011731486>
<@&502884371011731486>
!ban 1084592471218065510 Spam
Jack.#3448 was banned
You can use the Quaternion.Lerp function to smoothly rotate a transform around the y-axis with a limit (sorry if the reply is late and youve already found a solution) โฅ๏ธ
Hi, I have an interface in which Im predefining one method. In that method, I want to use GetComponentsInChildren<Button>() but to do that I have to somehow force classes that implement that interface to inherit from Monobehavior. Does anyone know how to do that?
public interface IEquipe
{
protected abstract string EquipedText { get; }
protected abstract string EquipText { get; }
private void ChangeState(bool equipe, string name)
{
if ((!equipe && ShopData.GetInstance().IsPurchased(name)) || equipe)
{
string message = equipe ? EquipedText : EquipText;
foreach (var button in GetComponentsInChildren<Button>())
{
if (button.tag == "PriceButton")
button.enabled = !equipe;
}
foreach (var text in GetComponentsInChildren<TextMeshProUGUI>())
{
if (text.name == "PriceText")
text.text = message;
}
}
}
}
uh @plucky inlet?
Ill try that, makes a lot of sense lol
what is Allocator.AudioKernel? Docs say it's "Allocation associated with a DSPGraph audio kernel." but this doesn't tell anything to me
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
in this script i am trying to make a shotgun that has a fire rate ad bullet spreading but it doesn't shoot
(the script is attached to the gun)
Are you using the new or old input system?
old input system
Err I haven't used the old one in so long I have no idea if that could be the problem
I'm trying to create a reusable component for a TextMeshPro with a Quad background, without having to use Canvas. The main goal is to create these programmatically, but it's also nice to see a preview in the editor. I had to use playModeStateChanged to avoid the generated quad GameObject persisting after leaving play mode. Is this reasonable at all, or am I doing something wrong?
https://gist.github.com/vittorioromeo/036b391c5cc928f8f7a73c4c70f19396
Debug.Log is step 1. Print out your variables
AudioKernel
Hi, has anyone used Integrated App Purchases? I want to set an item to 0 cost but the editor wont accept it for android (apple has a free tier)
setting the Price to 0 or 0,00 just empties the box
Im trying to simulate a rotating axle like this. To do this ive set up an empty game object as the axle root and connected two children to it at the end points. When I rotate the parent of them this gives the desired behaviour. Im however, not sure how to do this in code ? I want a hard limit to the rotation, e.g it cant turn more than 30 degrees in either direction.
Quaternion targetFront = Quaternion.AngleAxis(-steeringParameters.axisMaximumDisplacement, axisFront.up);
Quaternion targetBack = Quaternion.AngleAxis(steeringParameters.axisMaximumDisplacement, axisBack.up);
Quaternion nextFront = Quaternion.Lerp(axisFront.transform.localRotation, targetFront, Time.fixedDeltaTime * agentController.moveAxis.x);
Quaternion nextBack = Quaternion.Lerp(axisBack.transform.localRotation, targetBack, Time.fixedDeltaTime * agentController.moveAxis.x);
axisFront.transform.localRotation = nextFront;
axisFront.transform.localRotation = nextBack;
Im not quite sure how to do this -- ive tried using Quaternion.AngleAxis but this is wrong and I cant quite figure out why :)
Just represent the current rotation as a float. Add or subtract from this float to rotate. Clamp the float to your desired angle range.
Then just drive the object's rotation from it
Right, since its a local rotation around a single axis i wont have trouble with gimbal lock
thanks!
Is this right?
{
get { return currentShield; }
protected set { currentShield = currentShield + value < 0 ? 0 : value; }
}```
No this will cause a StackOverflowException immediately
You need to use a separate backing field
private int _currentShield; for example.
Your current code recursively calls the property.
How do I override the operator for >= or <= for a class? Is this even possible?
i can't find it on the internet, can only find == or !=
Is this a good way to do it? Does this work for >= as well? Or would I need to define the == or the >= operator seperately?
public static bool operator >(Timestamp time)
{
if(this.hour > time.hour || this.hour == time.hour && this.minute > time.minute)
{
return true;
}
else
{
return false;
}
}
It must be defined separately.
if(this.hour >= time.hour && this.minute > time.minute)
Hi, how can I "unlink" the wheels from the car body so that the suspension doesn't work like this:
this is what I have:
https://youtu.be/TyiHciltZfk
but this
https://youtu.be/CdPYlj5uZeI?t=729
A detailed look at how we made our custom raycast-based car physics in Unity for our game Very Very Valet - available for Nintendo Switch, PS5, and Steam.
BUY NOW!! https://toyful.games/vvv-buy
~ More from Toyful Games ~
- Physics Based Character Controller in Unity: https://youtu.be/qdskE8PJy6Q
- Instant "Game Feel" Tutorial: https://youtu.be/...
what you should do is think about your lack of use of brackets for your calculations
im confused, what does <T> mean
Can someone help, I don't know what the issue is on this code.
<T> is a generic parameter that helps to create generic functions where you can pass in different types
what is it meant to do and what is the problem?
as in what does it do wrong
I'm trying to build my project for iOS and the iOS resolver comes up and says
"Failed to install CocoaPods for the current user.
It will not be possible to install Cocoapods in the generated Xcode project which will result in link errors when building your application.
For more information see:
https://guides.cocoapods.org/using/getting-started.html
'gem install cocoapods --user-install' failed with code (1):
Building native extensions. This could take a while...
WARNING: You don't have /Users/XXX/.gem/ruby/2.6.0/bin in your PATH,
gem executables will not run."
I've read as much as I can find on various forums about this specific issue and tried to follow the advice but cannot fix the problem. Partially, I think it's possible I am making a dumb error when following the advice because admittedly, I'm not so familiar with package managers, dependency managers, etc., so unless it is fully spelled out for me what to do I could be following advice wrong. if anyone has an understanding of what this error likely is (maybe you have encountered it yourself) I would really appreciate your help. also, I see that under Assets>Mobile Dependency Resolver>iOS Resolver>Settings, I can uncheck things such as "Use shell to execute cocoapod tool" and "auto install cocoapod tools in editor" but I have not seen any advice regarding this settings panel. should I do something there?
thanks
It "teleports" a gameobject into another gameobject position, basically just changing the transform position onto the other
Shouldn't be any problem but there is
thats what its meant to do correct?
Yeah, make a gameobject's position to another position
No issues, debug.log passed all, made it in a way that the list of gameobjects that I get the gameobject position from is atleast 50 generated but yet its not working
anyone know how to program a mechanical belt system that transfers complete torque but doesnt break for reasons stated in image
While thinking about it. Scriptwise you should have values for each wheel, the torque from the chain and additional torque from those gravity parts. And then the calculation of the summarized torques should give you the possibility to stop or accelerate the gears correctly. The belts would just be a visual representation and not really affecting the gears
Like each gear has a list of connected gears and their torque forces on "this" gear
I would say this is precisely the type of physical simulation problem that PhysX is bad at simulating and you'd probably be better off with a custom implementation or an asset like this:
https://assetstore.unity.com/packages/tools/physics/filo-the-cable-simulator-133620
Oh wow, that looks quite handy, thx for sharing ๐
Hi everyone. I'm trying to lit sprites differently, while keeping them in the same Sorting Layer (so that transparency sort mode works as I intend). I'm using URP, but apparently I don't have Light Layers available.
If there's no workaround, is there a way use Custom Axis transparency sort mode to have sprites behave like they're in the same Sorting Layer?
I'm on URP v14.0.5
Light layers seem to be implemented differently, I'm checking changelog and the functionality is now under "Use Rendering Layers". Thank you!
where is documentation for Unity.Mathematics?
neither this https://docs.unity3d.com/Packages/com.unity.mathematics@1.2/manual/index.html
nor this https://docs.unity3d.com/Manual/index.html
looks like a documentation..
If you want the scripting API it's here:
https://docs.unity3d.com/Packages/com.unity.mathematics@1.2/api/index.html
but why it's formatted in different way than whole Unity docs?
It's a package
All packages have separate sites like this
doesn't make sense to me, but whatever, thanks for the link
If you refer to a private variable in a method, and then pass that method as an Action to some other class, will that class be able to invoke the method?
Or how does that work
do you mean having something like public void Something(float floatNum){ floatNum += 1.0f) then calling private float aCoolFloat; Something(aCoolFloat)?
or do you have some example code i can look at
In this case I'm modifying a private variable by another private variable. But I want to pass the method to another class (DelayedTrigger) which handles delayed triggers (since I want this method to be used after a certain number of rounds). And I want DelayedTrigger to be able to handle any kind of trigger, ideally
local variables can't have accessors
I would need to see the code to get what you mean
If you pass and execute the method as a delegate, it would execute exactly the same way as if you called it normally.
Oh, so invoking the method is the same as using it in it's original place? So it can modify private variables and etc
But, yeah, without an example, it's hard to understand what you're talking about.
just post a hastebin or something
it is executed in it's original place. It's just called from somewhere else.
this is all I needed to know, I think
how do i display big numbers without decimal points or scientific notations?
ive tried toString but it doesnt change anything
Hello
@kind wolf I think its .ToString("F2") or something like that for 2 decimal points
i dont want any decimal points tho
then ("F0")
myFloat:D``` to show without any decimal places
:D
like this?
yes
it gives me an error
sorry apparently the x:D syntax is only available in string interpolation
which error
massText.text = $"{mass:D}"
Oh yeah it's F0 indeed
or just use F0 as you had previously
Apparently D is only supported by integral types. TIL
F0...
yea this worked
massText.text = $"{mass:F0}"
massText.text = mass.ToString("F0");
Pick one
oh those are the same thing
@leaden ice btw Physics.SyncTransforms or whatever did not work
sooooooooooooooooooooo\
ig its doomed
what is that question mark for @leaden ice sorry for ping again i just assume you left lol
the question mark is for idk what you're talking about. if it's an earlier discussion we had, refresh my memory
raycasts not working on linux
.
Yes I remember now the shrug is "idk"
well i guess im doomed
Anyone know why this only shows up when i try to build my game? its having a problem with using UnityEditor.Animations;
YOu're trying to use editor only code in a build
notice the UnityEditor namespace
that's ๐ซ
Ah, im new so forgive me if its a dumb idea on how I did it. I have an array of animatorcontrollers each having a different animation. When the game starts it takes the selected one and basically equips it. If I remove that then it just underlines everything in visual studio. Any alternative ways I can research or lookup instead of doing what I did?
what's the gameplay goal of what you're trying to do?
Player buys a skin for cat and then equips it when the game starts the cat has a different animation based on what was bought and equipped
You should be using this
https://docs.unity3d.com/Manual/AnimatorOverrideController.html
Alrighty ill readup on it i appreciate the advice
oes anybody know how to upload a Vroid model to unity
i have a MutationStat class and a MutationSO scriptable object class that just stores a MutationStat and another value
i have a constructor that takes in the scriptable object: ```public MutationStat(MutationSO mutationSO)
{
stat = mutationSO.mutationStat.stat;
negative = mutationSO.mutationStat.negative;
canBeNegative = mutationSO.mutationStat.canBeNegative;
unscalingWithRarity = mutationSO.mutationStat.unscalingWithRarity;
mutationTarget = mutationSO.mutationStat.mutationTarget;
modType = mutationSO.mutationStat.modType;
}
then i get a list of the scriptable objects and make a new MutationStat```List<MutationSO> SOList = new List<MutationSO>(MutationSODBService.GetAllMutationStatSO());
for (int i = 0; i < SOList.Count; i++)
{
MutationStat mutationStat = new(SOList[i]);
...
}
for some reason this ends up with the base scriptable objects being modified, anyone have any idea why that might be happening?
before & after
Nothing in the code you shared modifies anything
But all you're doing in the code you shared is passing references to your SOs around
if you think you're making copies of the SOs, you're not.
thought i was making a new one with MutationStat mutationStat = new(SOList[i]); ?
That's making a new MutationStat
not a new MutationSO
For this stuff:
stat = mutationSO.mutationStat.stat;```
You'd have to explain what those fields are
they are probably reference types
public class MutationStat
{
public Stat stat;
public bool negative;
public bool canBeNegative = true;
public bool unscalingWithRarity;
public int mutationTarget;
public StatModType modType;
public MutationStat(MutationSO mutationSO)
{
stat = mutationSO.mutationStat.stat;
negative = mutationSO.mutationStat.negative;
canBeNegative = mutationSO.mutationStat.canBeNegative;
unscalingWithRarity = mutationSO.mutationStat.unscalingWithRarity;
mutationTarget = mutationSO.mutationStat.mutationTarget;
modType = mutationSO.mutationStat.modType;
}
}
where's the code that modifies the values?
{
MutationStat mutationStat = new(SOList[i]);
int weight = CalculateWeight(SOList[i]);
if (!mutationStat.negative)
{
positiveMutationStatList.Add(mutationStat, weight);
if (mutationStat.canBeNegative)
{
mutationStat.stat.SetBaseValue(-mutationStat.stat.Value / 2);
mutationStat.negative = true;
negativeMutationStatList.Add(mutationStat, weight);
}
}
else
{
negativeMutationStatList.Add(mutationStat, weight);
}
}```
What is Stat?
Can you share the code for Stat
it's probably a class
meaning your MutationStat and MutiationSO both share a reference to the same Stat object when you do this:
stat = mutationSO.mutationStat.stat;
it's a class which holds a double value and a list of modifiers
so modifying one is visible in both
key word being class
you'd need to make a new copy of it in the constructor for MutationStat to make them independent
yep that did the trick, forgot that lol, ty a bunch
hello i am trying to create my own asset pack to host on github and i am getting close, only issue is that i cant seem to find a reference to reference to "UnityEngine.CoreModule" so its giving me issues with some transform stuff.
You just need to make sure this is NOT checked
you shouldn't need an explicit CoreModule reference
let me try but i am pretty sure issue still persists, i didnt have that ticked from the start
what errors are you getting
any DOTween users? It's a bit annoying that DOKill is not chainable, because this would have been much shorter if it was. or is there a better way to do hover animation?
public void OnPointerEnter(PointerEventData eventData)
{
transform.DOKill();
transform.DOScale(1.1f, .16f).SetEase(curve);
text.DOKill();
text.DOColor(hoverColor, .16f).SetEase(curve);
}
public void OnPointerExit(PointerEventData eventData)
{
transform.DOKill();
transform.DOScale(1f, .16f).SetEase(reverseCurve);
text.DOKill();
text.DOColor(startingColor, .16f).SetEase(reverseCurve);
}
Packages\DungeonForge\Runtime\PcgScripts\EditorSideScripts\PCGManager.cs(302,51): error CS1061: 'Transform' does not contain a definition for 'AddComponent' and no accessible extension method 'AddComponent' accepting a first argument of type 'Transform' could be found (are you missing a using directive or an assembly reference?)
This is not an Asssembly issue
this is just a run of the mill "you wrote code that doesn't compile" issue
Only GameObject has AddComponent
Component / Transform do not
i am sure this does compile as i had it on my normal scene
doubt
Does not and has not ever compiled in Unity
but this does
public enum IconTypes
{
Gems,
Hearts,
Coins,
WoodChestKey,
GoldChestKey,
DiamondChestKey,
HeroChestKey,
DuplicateHeroShards,
RandomHeroShards,
Xp
}
I want to create a dictionary with each type with an int of 0...whats the best way to do this?
can't figure out how to do it with a foreach loop
I would say there's no need to prepopulte the dictionary with 0s
var comp = this.transform.AddComponent<VoronoiMA>();
this does compile fine
is a line of code that doesn't compile.
everything compiles fine lol
if that compiles you've added an extension method or something
figure I would want to initialize it to 0 as other code might try and check the amount...and if the dictionary doesn't have the key it will throw errors
just use TryGetValue
public int GetGems(IconTypes it) {
dict.TryGetValue(it, out int result);
return result;
}```
0 is the default value for int so this will just work.
fair enough
reguardless, I like the loot/feel of pre-populating the values....so Im going to
is there an easy way to do it for each enum ๐
tbh if it works with gameobject.add then i have no issue in using that way let me give it a go and do some refactoring
I was looking through that
couldn't figure out a way to get the output as IconTypes."insertname"
seems to just return name as string or int
which isn't of the Enum type
you just cast it
or this example from that article seems to just do it too:
foreach (ConsoleColor color in Enum.GetValues(typeof(ConsoleColor)))
{
Console.ForegroundColor = color;
Console.WriteLine($"Foreground color set to {color}");
}```
If you can, now there's the generic version of this method available
Enum.GetValues<T> returns T[]
ooh yeah def use that if it's available^
foreach (IconTypes icon in Enum.GetValues(typeof(IconTypes)))
{
ConsumableList.Add(icon, 0);
}
this works great thanks ๐
Hey, got a quick question. I have a float that ranges from -40 to 150. How do I convert that float to a number between 0.0 to 1.0?
guys i just did a lot of stuff in play mode is it possible to save everything i just did without losing it when i exit play mode
Mathf.InverseLerp
Ok im gonna ask again, because I really want this to work. Is there any reason a raycast would work differently on windows VS. linux? I have a system that im trying to make to pick up items in my game, for some reason, when I make a raycast at the exact same position (as in "Ray Created: Origin: (401.40, 3.38, 420.94), Dir: (-0.15, -0.37, 0.92)"), it works on two different windows machines, and my editor, but not on linux. any reason why?
Thanks!
btw my ray IS still hitting stuff
just not what i expect
if i cast the same ray beforehand without filtering, it hits stuff, just never hitting the item that im trying to grab
maybe there is a way to render a ray in the game?
that would be useful for debugging
hi ,
could someone explain to me what im doing wrong in a simple math equation ?
float initial = 0;
float final = 0 ;
float additional = 5;
final = initial - additional;
/// final is always = 0
// expected value for finale = -5;
does the above equation make sense ? or did i do something wrong else where ?
the problem is somewhere else
Looks like it's -5 to me
https://dotnetfiddle.net/zNVxSV
Test your C# code online with .NET Fiddle code editor.
yes, i debuged all of them
Looks good to me, C# hasn't lost its mind yet
show your real code ๐ @solemn raven because something else is going on here.
can you show how you printed them
do you guys have your animations code all in a seperate script or do you leave it in ur movement script
btw for the 3rd(?) time now here is the code for this
public void Pickup_Pressed(InputAction.CallbackContext ctx)
{
Debug.Log($"Pickup Press: {ctx.performed}");
if (!ctx.performed)
return;
RaycastHit hit;
Ray ray = main_camera.ScreenPointToRay(Mouse.current.position.ReadValue());
Debug.Log($"Ray Created: {ray.GetPoint(0f)}, {ray}");
Physics.SyncTransforms();
if (Physics.Raycast(ray, out hit))
{
Debug.Log($"[Test] Ray Hit An Object: {hit.transform.gameObject.name}");
}
Physics.SyncTransforms();
if (Physics.Raycast(ray, out hit, inventory_grab_range, mask)) // Do a Raycast with only layer 8 (Items)
{
Debug.Log($"Ray Hit An Object: {hit.transform.gameObject.name}");
Transform hit_transform = hit.transform;
GrabItem(hit_transform.gameObject);
}
Debug.Log("Cast Attempts Done.");
}
the first print always runs
and the second one
and the third one
but not the fourth
ok yh this works and things did sort of do what they should have thanks dude
also that Physics.SyncTransforms() call is added as a debugging measure as suggested by someone here
if you are wondering about it
but I havent figured out any reason that this shouldnt work
Thanks actually ๐ ๐
i was writting down the function on discord , then it hit me, i was actually changing the value of _final not final , that is why its always 0 ๐
thank you โค๏ธ
its like the hitbox on my items just is smaller with linux but that makes actually no sense
and SOMETIMES i do hit the item
just 99% of the time not
I have a transform hierarchy like so: Parent - Child - ChildChild. When I call ChildChildTransform.Rotate(vector.right, someAmount); everything works as expected, until the Child object also rotates. At that point, my ChildChild object accumulates errors and wobbles around a little (as seen by random values popping up in the y and z axes in the inspector). They can get large enough to be perceptible, which is no good.
To be clear, the Child object basically does the same thing, only it rotates around Y (and is obviously doing just fine).
Any clues as to what could be causing this and how to fix it?
what are you trying to achieve
2 independently rotating axes, essentially
A turret
something else?
Keep your own yaw and pitch floats
rotate the objects with transform.localRotation = Quaternion.Euler(0, yaw, 0) and likewise for the pitch on the other object
Hmmmm.
Could work... let me think, quite a few things to consider with that ๐ค
Yea, that could work. That potentially has quite a few implications on the rest of my code, but might just be fine. Thanks, I'll see where that leads. Still, curious why that's happening. Any idea?
Hi there
I would like to ask an advice
I have this code
void Update()
{
// Move Forward
if (Input.GetKeyDown(KeyCode.W))
moveForward = true;
if (Input.GetKeyUp(KeyCode.W))
moveForward = false;
}
private void FixedUpdate()
{
CalculateThrustForce();
}
private void CalculateThrustForce()
{
float maxThrust = maxForwardThrust;
float timeToMaxSpeed = topForwardSpeedTime;
if (moveForward)
{
thrustAcceleration += Time.fixedDeltaTime;
if (thrustAcceleration > topForwardSpeedTime)
thrustAcceleration = topForwardSpeedTime;
}
if (moveBackwards)
{
thrustAcceleration -= Time.fixedDeltaTime;
if (thrustAcceleration < -topBackwardSpeedTime)
thrustAcceleration = -topBackwardSpeedTime;
maxThrust = maxReverseThrust;
timeToMaxSpeed = topBackwardSpeedTime;
}
if (!moveForward && !moveBackwards)
{
if (thrustAcceleration > 0)
{
thrustAcceleration -= Time.fixedDeltaTime;
if (thrustAcceleration < 0)
thrustAcceleration = 0f;
}
else
{
thrustAcceleration += Time.fixedDeltaTime;
if (thrustAcceleration > 0)
thrustAcceleration = 0f;
}
}
float thrust = Mathf.Lerp(0, maxThrust, Mathf.Abs(thrustAcceleration) / timeToMaxSpeed);
rb.AddRelativeForce(new Vector3(0, 0, thrust * Mathf.Sign(thrustAcceleration)) * thrustMultiplier, ForceMode.Acceleration);
}
Any suggestion to make that code simpler and cleaner?
First of all, use input axes rather than KeyDown and KeyUp
Then multiply those with your thrust and whatnot, rather than doing booleans

Does anyone know how I could draw a custom display in a unity editor I am making? I want to make a window with a scroll bar and draw lines inside it, etc for my level editor
is there something kind of equivalent to a drawing panel I can use? I'm sure you guys have used something like I have when you were learning where you can code to draw shapes, etc on a panel. I'd like to use something like that
The GetAxis returns a value between -1f and 1f, right?
Yup
kk
I need some help here please
private void CalculateThrustForce()
{
float thrust = Input.GetAxis("Thrust");
float thrustDir = Mathf.Sign(thrust);
thrustAcceleration += (Time.fixedDeltaTime * thrustDir);
thrustAcceleration = Mathf.Clamp01(thrustAcceleration);
float thrustAmount = Mathf.Lerp(0, maxThrust * thrust, Mathf.Abs(thrustAcceleration) / thrustTime);
rb.AddRelativeForce(new Vector3(0, 0, thrustAmount * thrustDir) * thrustMultiplier, ForceMode.Acceleration);
}```
Canยดt figure out how to apply fore forward or backwards
At this line ```haskell
rb.AddRelativeForce(new Vector3(0, 0, thrustAmount * thrustDir) * thrustMultiplier, ForceMode.Acceleration);
why not use rb.AddForce
AddRelativeForce applies it in local space which is basically the equivalent of AddForce
but surely the "thrustDir" variable determines whether the thrust is forward or backwards
If I use AddForce, the force is applied incorrectly
so there shouldn't be anything special you need to do to "add force forward or backwards"
although you are doing some weird calculations with the thrust variable then multiplying it by its sign without first taking the absolute value of the calculations
which of course means when you multiply the negative number by the negative 1 for its sign it suddenly becomes positive ๐
Yeah, I am kind of failing there
I see the issue
I am clamping between 0 and 1
I need to clamp between -1 and 1
i mean that's not the only issue
you need to either stop mutliplying by thrustDir or you need to take the absolute value of thrust before doing any of the other calculations
Let me explain you what I am trying to get here, I think that will be easier
you don't need to explain, you are only providing a positive value no matter what because of the multiplications by -1 when the value is negative
can you show me which line is wrong?
my dude what do you think a negative number multiplied by -1 ends up being?
sorry lol, I am very mentally tired rn
then take a break and come back to it with a fresh mind
Hey, i have an animator, with an animator state, which moves the transform of my gameObject. However, this animator state is never called, by transition with triggers, or something like that, but, my gameobject has his positions completely frozen, i cannot move it, can someone help me? :/
coding channel...hard to help with code without you posting any ๐
ok, i have this animator :
The "SwitchPhase" animator state contains the motion which moves the transform of the gameobject
but the transition from emptyState to SwitchPhase, is never called
i debug.log the code and check , and never called
sorry, didn't see the channel, mb
Does a struct return a copy of itself or a reference when used as a property { get; private set: }?
copy
Gotcha, is there a way for me to have to return as a reference?
I don't think the Unity C# version has access to ref fields
use a class
you'd have to make a ref return method (i think, i've not tried) or use a class
If I use it as a class, then it would be open to change public variables within
or just remember to set the variable back after you change it, don't make it private set
I want the public variables inside to be protected instead of just the parent class/struct
don't make your variables public then
I don't see what struct vs class has to do with that
public class Test
{
private TestStruct testStruct;
public ref TestStruct TestStruct => ref testStruct;
}
public struct TestStruct
{
}
This should work
Ill explain in 1 sec
That doesnt work with my situation
It can always work. Expose what you need via carefully curated public methods and properties. Make everything else private
I have a struct that holds a bunch of parameter variables for a director/manager class, the structs are presented as a variable in my director class that are exposed as private set properties so that I can read these variable at anytime while also having them change as i need them from within the director class
A struct works perfectly for my needs, the only problem is that i want to access these variables without forcing a copy of them every single time I need to
What's a "struct class"
Real
use a class not a struct if you want to pass references around rather than copies.
What are you gaining by using structs here exactly that you don't want to give up?
I have two groups of variables that I need constant global access to, like static variables, but they need to be changed exclusively by the director class and nothing else
Three options for that:
- When you want a "view only copy" of your object create and return a fresh copy, not the original.
- Make your class implement an interface that presents its data through read-only properties. Return your object as that interface instead of the concrete type when asking for the view-only copy.
- Make your class contain a struct. Pass the whole class reference when you want to be able to modify it. Pass around only the struct (copy) when you want just a view.
Ah, an interface for the struct is probably what Im looking for
for example check out https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.ireadonlylist-1?view=net-8.0. If you return a list as this interface somewhere, then the caller can read the list but not mutate it
If i typecast a struct into an interface, does it still create a copy of that struct?
Or can i do (IStructVar)(ref structVar)
The point is to use this in conjunction with a class not a struct
so you know you have a reference not a copy
I have a CardEntity that is created from a CardModel SO whenever a card comes into play (e.g. added into your deck). I'm now getting around to writing methods to render the card on screen, control its animations, interactions with the user, et cetera.
In previous games, I've sort of just stuffed everything inside MonoBehaviours with no real separation of concerns. I'd like to get out of that habit, but I'm struggling to figure out the soundest way to design this. My first instict is to create a separate UICardController that would live on a prefab, and have a method that lives on a factory class somewhere to create an instance and return the UICardController. I'm in doubt on if that's a solid approach though, and wanted to see if anyone had any wisdom to share ๐
Gotcha, thanks for your input!
does really noone have a clue on this? would i be better off asking in #โ๏ธโphysics ? i cant find anything on google about hitboxes or rays behaving weird on linux maybe im just stupid
Hello there, i have been wandering and searching for an answer but i can't find it, so i'm here to ask if it's good practice to use the method "Sigletoon" to change scenes or levels or is there a better way to doit.
Linux users are a rare breed so dont expect to get answers quickly
i mean i guess
Bumping your question is fine though, and yes ask in #โ๏ธโphysics why not
I assume by method "Sigletoon" you mean create a Singleton with methods to change scenes? If so - you're basically doing what the SceneManager does, just use that
Yea that's what i wanted to know, thanks (also for correcting me)
{
_enemyList.Remove(go);
PlayerUI.Instance.SetZombieRemainingText(_enemyList.Count);
}
We dont need to check for contains ? So we forget about it and remove directly ?
This method also returns false if item was not found in the List<T>
Euh ok but what that will change ?
_enemyList.Remove(go); will not occur a bug if the go don't exist on the list
correct, because it just returns false instead of throwing an error you don't need to check if the item is in the list before removing it
So for performance we don't do the check
unless you need to know whether the item is in the list for some other logic, then you do not need to do that check
ok ty.
I have WebGL game. Iam trying to save game with playerprefs and storing string of JSON. My Weapon class has Sprite icon which it gets from ScriptableObject who has reference to the sprite. How can I save and load sprite with JSON? I saw Resources folder which really messes up my structure of files. I saw storing sprite into raw texture and will be my next attempt but I would really like to hear if there is better way?
Also if somebody has better idea to save progress? I would really like to hear it. If playerprefs becomes problem and can't store so much info I think ill store files at persistentDataPath
var text = gameObject.AddComponent<TextMeshPro>();
Variable text is null after this line, but I do not understand how.
Hello
I do button for pause game
When I click it the timescale = 0 and menu show
But if I click the button behind the menu I can do that
How can I solve this?
Probably the obejct already has such a component or another Graphic
Seems like a #๐ฒโui-ux question
OK
AFAIR, Unity throws an exception if you try to add an existing component
nope
just returns null from AddComponent
btw in general you can add duplicate components
but there are certain that you can't. For example Graphic and Rigidbody
for those - it returns null
oh right, i stand corrected
private void SpawnZombie()
{
for (int i = 0; i < 32; i++)
{
int randomSpawnerIndex = Random.Range(0, _spawnerArray.Length);
Vector3 spawnLocation = _spawnerArray[randomSpawnerIndex].transform.position;
Vector3 randomPoint = new Vector3(Random.insideUnitCircle.x, 0f, Random.insideUnitCircle.y) * 5f + spawnLocation;
if (!Physics.BoxCast(randomPoint, _pfEnemy.transform.localScale, transform.up, out RaycastHit hit, transform.rotation, 20f, _spawnLayerMask))
{
GameObject go = Instantiate(_pfEnemy, randomPoint, Quaternion.identity);
_enemyList.Add(go);
break;
}
}
}
Goal is to spawn enemy on a spawner. What do you think of my script and how you will do it ?
@leaden icethank you!!
how can i interact with ui while my cursor is locked?
tab or dirrection arrows are a good option
if you camera is rotating then the cursor is still in the center.
another option is to enable cursor movement while UI is up.
ill see if i can do a ui panel sort of thing
Is there anyway to add options to that menu through extensions? I need a SwithActive() Method there, to just switch it from active to deactive, and visa versa
I know I could add my own component to have this functionality, but it is so basic that I would just want it everywhere.
I have no idea if extension methods appear in that list, but you could try it and see
Yeah no, which I guess I could have forseen from Unity
adsRotation = -Quaternion.LookRotation(transform.InverseTransformDirection(gun.GetSight().forward), transform.InverseTransformDirection(gun.GetSight().up)).eulerAngles;
combined with
float adsCurveValue = adsCurve.Evaluate(adsWeightLerped);
arms.localPosition = adsPosition * adsCurveValue;
aiming down sights while an animation is playing (like reload animations) makes the viewmodel go abolutely crazy
Is looks to be using assembly definitions (I imagine in the Runtime folder) can you check that that's configured correctly?
i am an idiot never mind 2 hours wasted
You should ask in #archived-networking and post code using our guidelines !code
๐ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
ah okay Sorry
is there any way i can show a c# record obj in the inspector?
Records use properties, and their fields are readonly so they are not serializable. So they are not capable of being displayed/saved without a custom setup.
i see, ty
Why cant I script ๐๐
it expects a } ๐ค
If your IDE is not underlining errors in red you need to configure it properly so you can see obvious errors and fix them !ide
If your IDE is not autocompleting code
or underlining errors, please configure it:
โข Visual Studio (Installed via Unity Hub)
โข Visual Studio (Installed manually)
โข VS Code*
โข JetBrains Rider
โข Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
where
Configure your IDE
line 117
they won't learn how to fix this themselves if you spoonfeed them
Please don't provide no-context answers to people without configured IDEs
next to the script name is (line #, character #) and the following message explains it all
configure your IDE
Configure your IDE as you have been directed to before attempting to get an answer to this basic question
- configure your ide as people said
- count the braces ig
I havenโt been on unity In a LONG Time what it that? Im sorry if Iโm fcking stupid
Hello!
I am attempting to make a platformer type game for a game development class at my high school. I noticed that on the school computers, the game's physics were much floatier than on my home computer.
I was wondering how to fix the problem without changing the massive amount of code I have; re-writing it to fit the fixed update loop for ONLY the physics, and having the update loop only for inputs (since it seemed like a lot of work for the fixed update loop to just fail and go over the physics stuff twice)
TLDR:
I essentially have everything in an update loop, and don't want to have to reformat literally all code for every physics-influenced object
Extra question:
Can I technically make this work by proportionally setting the masses depending on the time seen within Time.deltatime?
are you handling physics manually or using rigidbody?
rigidbody
and the forces/accelerations you are applying are frame rate independent?
You wouldn't use it for forces anyway. But they need to be applied in fixed update if you want deterministic behaviour.
So just move the parts where you add forces, to fixed update.
they might be using ForceMode.Impulse or .VelocityChange tho
which will need to be multiplied by Time.deltaTime i think
I'm using ForceMode2D.Force
just try this then
Depends on what behavior they expect, but normally you wouldn't use delta time for that either.
problem: the part where I add forces is tied to my inputs, and I don't want to sacrifice input consistency
pain.
I don't understand what the problem is..?
How is it tied?
Is it using the new input system or something?
no
so like, I'm using conditionals each frame to check for inputs.
then based on that, I add a force
Okay..? Then just cache the input conditions and use them in fixed update.
Also, could this technically work? I'm just wondering just in case someone knows
No. It's a terrible solution.
The actual solution is very simple with a bit of refactoring.
You can get continuous inputs in FixedUpdate, its not a problem.
At least if youre polling like with GetAxis or whatever the new system uses
I'm using Input.GetAxisRaw and Input.GetButtonDown a lot
I'll probably just store the values of the inputs in variables for the fixed update loop to use and reset each time it updates
idk
At least thats what I got from dlich
GetButtonDown must go to Update yeah. But if you use it to add a one-shot force (like a jump with ForceMode.Impulse), you can add the force directly in the Update function, it will get applied next physics step anyway
You don't really need to modify it at all (assuming youre doing something like if(Input.GetKeyDown(jumpKey) rb.AddForce(jumpForce, ForceMode.Impulse);)
But continuous forces you should do in FixedUpdate
ok
You don't need to reset anything I think
ngl I dont know how continuous forces are even set up
I'm just calling the addforce once, and thats about it
With continuous I mean something like walking, which gets called potentially every frame and is time-dependent
Don't use ForceMode.Impulse with those btw
yeah I won't
I'm just using velocities for that
and, I think I definitely need to change the force value for Impulse mode
since I just used it, and my character jumped straight off the screen, lmao
This good old chart explains how forcemodes work
https://i.redd.it/6y8myu3ruxo71.png
so how would I make my impulse the same as the force-mode?
without using Time.deltaTime?
Never use deltaTime with forces
I understand that
Oh you would just give it a smaller value
idk ill just mess around with some stuff
Like around 50x smaller value
can i ask a question?
No
womp womp
People that say that are not allowed to ask questions
1 question per person and you just used it for this?
lol
haha
If you learned the lesson, go ahead and ask your question
how would you go about detecting the bottom half of a collider?
Detecting in what sense?
When colliding or what?
say a raycast hits the top half/bottom half with a seperation in the middle
to detect something like feet/torso or will i have to make seperate colliders
You could convert the hit position to that object's local coordinates, and check its y
But multiple colliders would be more intuitive IMO
Ideally, you'd make separate colliders(probably triggers) for the bones.
Often, if you have a ragdoll setup, you'd use the ragdoll colliders for that.
Is there a way to typecast a SerializedProperty into a custom class like TestClass or something? Or at the very least edit its values like TestClass.value and apply it to the property through the editor using a custom editor class?
Hi!
Does anyone know why my AudioSource is being removed when I go in "Play Mode"?
something is probably destroying it
MyClass example = (MyClass)myProp.boxedValue;
You can also use FindPropertyRelative to get its serialized fields
Did you answer my question or someone elses?
yours
Do you know what might be destroying it?
There's no "Gameobject(destroy)" hooked on any script
considering i've not seen your project or your code i have literally no way of knowing
Most likely your code
Different code
It's only this code
Thanks! In order to reverse it after I make any changes, do I just do myProp.boxedValue = (object)example;?
I'm sure you have other scripts in your project
is the issue actually that the reference in the inspector is being set to null and not that the audio source itself is being destroyed?
If you want to make changes it's usually better to do it through the serialized properties
Also that OnKeyDown will not trigger consistently https://unity.huh.how/programming/input/built-in-input/input-in-fixed-update
Alright, so [SerializedField] instead of public?
if i was right about the issue that likely isn't going to change much. you'd need to remove that line from Start since the object clearly doesn't have an AudioSource component attached to it
check if audio source and scriptffs are actually on the same gameobject
u may have component ref assigned but set to null in start
That fixed it! Thank you so much
All of you I should say
So im trying to make ladder climbing and i have this value that determines which direction you climb in depending on where you are looking
the problem is, if the direction you are looking in is the center (aka 0) you stop moving
Is there a way to make it so that a float is never 0?
Mathf.Round(player.cmPosition.forward.y)
heres what determines where you move
Vector3 direction = player.transform.up * Mathf.Round(player.cmPosition.forward.y) * player.currentinputvector.y; //allows player to climb up or down depending on where they look
IDK how to describe it
round it on another line, then you can use a ternary or if statement to check if the value is 0
I really need some help understanding why my mesh with procedurally generated vertices doesn't work in prefabs. I have this setup:
- GameObject
- TextMeshPro
- Quad
The GameObject has my script TextWithBackgroundController, which holds a reference to the TextMeshPro and the Quad. In its Update, it changes the Quad's vertices via quad.GetComponent<MeshFilter>().mesh.vertices in order to create a background for the TextMeshPro. This works perfectly in both play and edit mode.
Now, I'd like to make a prefab out of these three objects. When I do so, and spawn a new instance of that prefab, the mesh doesn't render at all. The debugger shows that the vertices are set correctly, but that there are no triangles.
I can fix the issue by manually going into the new Quad, and changing the mesh from "Quad" to "Quad Instance" in the mesh filter component.
I don't get it at all. Why does the prefab not render? Why does the mesh not get saved in the prefab? Why does changing the mesh manually fix the issue?
The source code for my script is here: https://gist.github.com/vittorioromeo/d500c347465f5cc3555001d00a1dd6cc
This is really driving me nuts, I don't understand this behavior at all.
thanks
if (collision.gameObject.TryGetComponent(out IDamageable damageable))
I do this for apply damage to a target but some target are friendly and so can't damagable between then how you can know if you can damage the other target or not ?
this may be an advanced question, is there a way to know how many size that a specific API/package occupied in built app?
Well for one you're not assigning any triangles to the mesh.
For two, kinda struggling to understand the point of this script. Couldn't you just use a world space canvas with a Content Size Fitter to do this more easily?
Not really a code question but https://docs.unity3d.com/Manual/ReducingFilesize.html
thx
The part I don't understand is that the are triangles in the original mesh that I am creating the prefab from. Why aren't those being copied over to the prefab?
currently getting pissed off at the TrailRenderer for emitting even though it shouldn't be (I'm probably wrong somewhere I hope).
I wrote this as a workaround 'cause apparently the .emitting value needs one frame before it affects the trail.
private IEnumerator StupidOneFrameWaitCauseTrailRendererSucks()
{
trail.emitting = false;
yield return null;
currentAnimation = StartCoroutine(AnimateFromTo(GetIndex(), ContinueAnimation));
yield return null;
trail.emitting = true;
}
This should wait a frame after disabling emitting, then teleport it, wait one more frame - then finally emit again.
What ends up happening is the code sometimes working, as the picture shows.
The dead end up top is a successful jump, while the line from the bottom to the middle was a not-so successful one. Any ideas?