#archived-code-general
1 messages · Page 405 of 1
do I just not understand what you're suggesting?
the actual functionality of the page is completely unrelated to the component deriving from UIPage
it's just a compile-time-safe way to specify exactly what page I want, from anywhere in the code, without messing with strings or something else
Are these types used exclusively for identifying what kind of page you need to open?
I'd consider using ScriptableObject assets instead. They're very handy "keys".
The only issue is that you need to get references to those assets, which can be a nuisance in code
(it's great for stuff you configure in the inspector, though)
I would not try to abuse the type system to do this.
I was having similar headaches with my settings system a while ago
I had an enum type for each setting
That's the one thing I don't like. I have a fair number of fields like this:
[SerializeField] private FloatSetting fovSetting;
There's only one meaningful asset I can put in this field.
yes, pretty much, although it's not out of the question that they have some function overrides inside them at some point - I just add something deriving from a UIPage to the monobehaviour, and I can drag them into my ScriptableObject with all the page prefabs
so, importantly, you don't need to know exactly what kind of UIPage you have
yeah, I don't, although it'd be nice to be able to select a page type from an inspector
I'm currently looking at this
https://gamedev.stackexchange.com/questions/203385/how-use-inspector-to-select-a-system-type-not-an-instance-of-classes-inheritin
but that doesn't solve the issue of needing a OpenPage(Type uiScreenTypeToOpen) or whatever
I would not be too worried about having a method that takes a Type, given that the generic method only exists to provide a type
it's not like you're passing in an instance of a UIPage and operating on it
you're strictly just doing GiveMeThing<KindOfThing>()
This is especially true if nothing else in that function signature depends on the type parameter
The non-generic Instantiate is annoying because it returns a UnityEngine.Object
but that is not happening here
yeah but I'm working in a team - it'd be nice to have a compile time check of the type of page I'd want to pass in
I mean
a compile-time check that I'm not passing in junk
that will only get discovered at runtime
Using ScriptableObject assets as keys would ensure you can only pick valid pages (unless you like...create a new bogus instance of the type and pass that in on purpose)
That would mean you can forget to assign a reference, though
I've wound up writing validation code to make sure I don't have any missing serialized references
Also, you have to give up something if you're going to allow the type to be provided by a serialized field, rather than being hard-coded
The compiler can't reason about that
I think I'll modify the script I sent just now, and do some type of UIPageSelector or something... so that it's still selectable but without the risk of passing in junk
What's the issue here, am I understanding correctly that, you currently have Open<T>(), but because your inspector needs to open a page, so you need to add a new Open(Type page), and you are worried that other people might use the latter method when they are supposed to use the former?
does this properly return a random uint across its entire range of numbers? (other than the maximum number which is exclusive using random)
I'm worried it might overflow before casting to a uint
there's a 50-50 shot on it overflowing :p
Are you trying to get a uniformly random unsigned integer?
That will be very non-uniform
think about how rolling two dice works out
I guess I'd just generate a random int and then reinterpret it as a uint
Oh right
int what = Random.Range(int.MinValue, int.MaxValue);
uint result = System.Runtime.CompilerServices.Unsafe.As<int, uint>(ref what);```
<https://stackoverflow.com/questions/3600871/fastest-way-to-cast-int-to-uint32-bitwise>
...but I'm pretty sure I had to install a NuGet package to get access to that `Unsafe` type
You can also just do an unchecked cast, as suggested in the first answer
Importantly, you cannot just cast the int to a uint
also, this is not strictly correct
it excludes the maximum possible integer value
If I needed to avoid that, I would use System.Random instead
(Do you really need the full range though, what are you using it for?)
indeed -- is this going to be an RNG seed or something?
I'm trying to simulate GUID.NewGuid();
so just setting each of the 4 values to a random uint
i dont typically mess with memory stuff (like the difference between an int32 and a uint) but cant you just fix this by removing the + int.MaxValue?
uints don't have negatives
so if it were negative it would probably not work but I'm not sure
oh
cant you just replace int.MinValue with 0 and int.MaxValue with (int)uint.MaxValue
No because uints go twice as high as ints
This isn’t related to coding but I can edit a line on pro builder
They have an extra bit to work with
right, my bad
Generate a byte array of the appropriate size instead.
This isn't related to coding
then why ask here when #🛠️┃probuilder exists?
My bad just joined
Oh fun I get to work with raw binary data
That’s something I’ve only heard about
Never done it personally
just use System.Random to randomly generate the bytes ez
Is there a way to add new animations to an animator at runtime without overriding or replacing the controller?
From what I can tell, you're either stuck replacing existing animations or replacing the controller. I have a list of animation clips that I want to apply to a controller once an event's triggered in game.
Well I am guessing that’s what a byte array is
o wait, would it be possible to do (uint)(UnityEngine.Random.Range(...) + (uint)(UnityEngine.Random.Range(...))
It wouldn’t be uniformly random like fen said. There would be lots of duplicates
Like how 7 is the most common number on 2 dice
huh, damn, i guess i really need to brush up on my maths skills then lol
I had the same idea until he pointed that out
I had forgotten about two dice being not uniform
a quick search seems to give me a stackoverflow post that's doing the same thing. seems like that may be the right direction then
Indeed.
You can generate as many random bytes as you want
https://learn.microsoft.com/en-us/dotnet/api/system.guid?view=net-9.0
You can construct a Guid out of an array of bytes, or out of a span of bytes
(similar ideas)
seems like casting int to uint does exactly the same as reinterpreting with Unsafe.As anyway so if uint is necessary then just a simple cast is enough when generating a number from int.Min to int.Max
https://dotnetfiddle.net/GuM8mO
Ah, I guess this thing defaults to the unchecked overflow-checking context
sorry real life got in the way but it seems like you found some path forward
if you wrap that in a checked block, it throws up
but yes -- this is the correct thing to do if you want to create a System.Guid
Outside of using an override controller to create a new layer with that clip, it does not seem possible. And the one thing I could do seems incredibly jank
I have this code to start a challenge when the player enters a collider in the entrance of a maze, but for some reason the collider is not triggering the challenge
https://hastebin.skyra.pw/kanijacolo.csharp
Any idea why this is happening?
Is your log printing?
Debug.Log("OnTriggerEnter called with: " + other.gameObject.name); // Debugging log```
no
You seem to be checking if the player GameObject is the entrance trigger GameObject which is impossible, instead use OnTriggerEnter inside your PlayerScript and check if the player has collided with the trigger and if it has, then use a boolean or an event to tell the manager to start the challenge, vise versa for ending the challenge.
Show the inspectors of the two objects that are touching that you expect to cause this code to run
is this two colliders
script needs to be on same game object to get trigger events btw
Im using another gameobject with the manager
that's one collider. Show the inspector of the other object now. OnTriggerEnter happens when two different colliders intersect, and there are other requirements too.
they are the same
They are not touching each other, and neither has that script on it
so there is nothing to trigger
so I don't understand what your question is about
you shouldn't have the OnTriggerEnter on your manager as well, you should preferably have it on your player and talk to the manager when ready to start whatever you want
The manager script is not present on either of these objects so it's completely irrelevant
it is in a empty game object, and the colliders are assigned in the inspector
OnTriggerEnter must be on one of the two objects involved in the collision/interaction in order to run
So this script will not do anything
When I say the two objects I mean the two that are touching
so presumably the player and the thing the player is touching
One of the two objects must also have a Rigidbody
I don't know what you mean by that.
If you want to use OnTriggerEnter it has to be either a script on the player or on the object the player is colliding with
ok
I'm checking distance in a climb function every frame to see if the player has reached the destination but I need to convert the distance to a range of 0 to 1 to input into an animation curve so I can change the climb speed based on how far you still have to climb. But I'm struggling with how to do that. I currently just divide the current distance by the distance I saved before you start climbing but that gets me a range from 1 to 0, which, works, but I would like it to be reversed, I just don't know how.
Mathf.InverseLerp
I would like it to be reversed
Anyway this part is super easy if you already have the 1 to 0 value.
float reversedNumber = 1 - theNumber;
I'm not that bright when it comes to math stuff lol. thank you!!
annoyingly, there isn't a Mathf.Remap function built-in
inverse-lerping and then lerping with the result is very useful
A lerp is min + ((max - min) * lerp) so you can think how you can replicate the inverse
ha yea it would be convenient if it was just there 😄
(c'mon, maybe in Unity 7..?)
I make a math2 class for everything I wish was in the math function but isn't. (Like vector2 math)
oops that clamp vector function is messed up
woops
Any clue why Rider thinks the first method is a Unity event handler?
I don't see a unity message called "Observe" anywhere
I have to save a list of Item extending Scriptable Object to Json. Output to JsonUtility.ToJson looks like
{"item":{"instanceID":24430},"quantity":2},{"item":{"instanceID":24426},"quantity":10}]}
When I load the game the references to the Items are completely incorrect. They all reference an Item, but the wrong one. This happens sometimes but not all of the time and I'm not sure how to recreate it.
Can someone explain how Unity serializes/deserializes based on instanceID?
Correct, you cannot simply JsonUtility SOs like this
That's just the default behavior when you try to serialize a unity object
It writes out the instance ID (which is meaningless outside of the current play session)
Generally if you find yourself trying to serialize a Unity asset to JSON there's something wrong somewhere in your design.
Is this for like, saving an inventory or something?
yes exactly
I have an Identifiable class that contains a GUID. I use Json.NET, so I have a converter that serializes an Identifiable as its GUID, and deserializes it by looking that GUID up in a table
Maybe I should save the string id of the items, and have some class that references all Item SO and deserialize that way
Your two best options are:
- Serialize the name of the SO to be used with Resources.Load
- Serialize an AssetReference to the SO from the Addressables package
- Serialize some custom unique identifier that you have a way of looking up
That's a good option, it's my third bullet point
Perfect, thanks!
funny how this same problem has come up so many times
well only once since me
but it's weird that it happened twice
It's a super common use case
speaking of which I'm getting my byte array but I don't know really how to get the numbers out of it. I know each set of 4 corresponds to 1 unsigned integer, but I don't really know how to convert from bytes to integers in a simple way
BitConverter is what you need https://learn.microsoft.com/en-us/dotnet/api/system.bitconverter?view=net-9.0
oh yeah I found that then forgot it existed, thanks
alright it's still happening
I'm guessing it's actually the prefab logic being messed up, not the guid logic
what is "it" here?
this is an object that will be loaded for levels
it has my editorObjectProperties script on it
the GUID is normal in the project view but when instantiated its guid is 0
ok I don't think it's the prefab
I tried with a different property and it worked fine
Is this GUID actually being serialized properly?
The bulletproof way to check that would be to look in your prefab asset (literally throw it in a text editor) and see if it has meaningful values (:
I mean... I put [Serializable] here but I don't know if that actually means it's being serialized right
None of these internal values are serialized.
They aren't public and haven't been marked with [SerializeField]
ohhh
you can still see a value in the inspector because you've got some kind of custom editor
which is grabbing values from the actual C# object
So they'll exist on the prefab just fine...until you cause the prefab to get reloaded from disk, at least
like this?
sure, that'll tell Unity it should be serializing all four of the uint fields
I saw in your script you have some sort of JsonProperty thing but it didn't appear for me so I just ignored it
there we go
probably should not require a custom editor for that though
if you are serializing a guid to text, 4 uints take more space than encoding the guid as string
this is a custom guid
what does that change?
I'm not sure what exactly you mean by encoding it as a string
you mean like exactly what I'm doing up there?
or do you mean converting the uint data to string data
Ok so this is what I get for not hardcoding I guess?
each uint is 32 bytes, each character in a string is 1 byte, so unless each uint is 32 digits long, it's less space to save "1234 1234 1234 1234" than 4 uints of those values
any ideas on how to optimize animator code? right now they're running on a simple LOD system but it's still very slow with 1000+ animators being updated
a uint is 4 bytes
oops sorry i mistyped, yes 32 bits
anyway the difference is negligble anyway but i think that was their meaning
You should sort by self Ms or expand the hierarchy more.
not much I can do about this though
Can you share the animator setup? Is it a skinned mesh?
what are the 1000+ animators doing? they are unfortunately pretty expensive so you may need some more creative solutions to avoid that many of them
they're running when the camera is close, or else updating every 5-30 frames depending on camera distance
but I need them
what i mean is, what are they being used for?
to animate soldiers
can you disable them entirely at some distance vs updating every few frames?
I don't think LOD can do anything for the animator. It only affects meshes and materials.
1000 animated characters is not really realistic with gameObjects. You'd probably need to go into DOTS/ECS
if you want 1000s of animated soliders on screen you may need some more custom solutions than just 1000 skinned renderers with animators on them
DOTS scares me lol
tried it before
Well, it's that or some custom smartass lod system that simplifies the animation setup.
you can maybe do it with game objects but pretty definitely not with animators as well, perhaps at a distance you can swap them out with a clever shader that does some kind of basic vertex animation that looks 'good enough'
Or animated billboards
yeah billboards are definitely not a bad idea
just haven't been able to figure out a good setup for them, I've used them in this type of project before though
if this is an RTS maybe you could prerender a few angles of animation of the soldiers and use those on the billboards
ok so if I convert a uint to some bytes and then convert the bytes to string, how do I convert the string into bytes again
just do this for each character?
yup
that's what total war games do and it works well
i think they're just talking about doing uint.ToString() on each int and concating those into a single string
also lol, nice UI
but then I'd be storing a whole byte per digit
personally i wouldn't worry about the size unless you have some kind of crazy scale, just writing the 4 uints as bytes seems perfectly fine
You could pack 2 digits into a byte with bitshifting if you really wanted to.
hey all. running into an issue with ScriptableObject data being set to null at runtime.
I have an SO called SceneHandler (inspector panel in first image) . I can create a SceneHandler and assign a scene to it, and then create definitions for multiple PassageHandlers (which are basically the exits of a room and connect to other PassageHandlers in other SceneHandlers.
in the SceneHandler, the passages are saved in a list like this:
public List<PassageHandler> Passages = new List<PassageHandler>();```
if I try to print out some info about Passages, it works fine. (images 2 and 3)
but then..i hit play and everything breaks. (images 4 and 5)
the list of passages disappears from the inspector panel and the Debug messages show that the list has been deleted.
i can provide more code if needed but im really hoping this is a quick fix hehe. it took way too long to get this to work :3
You should share the whole relevant !code:
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
SceneHandlerEditor - https://paste.ofcode.org/vcCqJJHRRJ6maHYR5YGjbL
PassageHandlerEditor - https://paste.ofcode.org/NH4xTvCyJwhTYpNUFukanT
PassageEditor - https://paste.ofcode.org/ysAizWcuVnmzB9Ra6UzUP
SceneHandler - https://paste.ofcode.org/34nuVSkned5edS7urt9nPUj
PassageHandler - https://paste.ofcode.org/4D8H4NiZdZkTW7x3difVpV
Passage - https://paste.ofcode.org/33BEjWmi7DPmvZtiW4NTPik
it looks like you have a custom editor for the SO, is PassageHandler actually a Serializable type? otherwise any values you put in it won't persist
i tried adding [System.Serializable] to the top of my PassageHandler but it didnt seem to change anything
not sure if thats the correct way to serialize it
oh it's an SO itself, so it is serializable by default
ah
ok so it looks like you're creating new instances of PassageHandler and adding them to the list, however i don't think this will persist after closing the editor or entering play mode because PassageHandler is a ScriptableObject which is an asset type and you aren't actually saving the asset anywhere
that makes sense
i don't think you can just make new SOs with new and have them get serialized
i'd need to actually create an asset for each PassageHandler when i make it?
if you want it to be an asset yes, otherwise you could just use a serializable class
it doesn't look like you really need it to be an SO on its own, it could just be a plain class marked with System.Serializable
if you do want it to be a full asset, it's possible to save the asset as a 'sub' asset of another, which might be worth looking into
nah i dont think i need it to be a full asset. it should only need to exist within the SceneHandler
in that case you can probably just make it a serializable class, i think just dropping the inherited ScriptableObject, and marking with Serializable will work, tho I think you may need to refactor your custom editor for it into a property drawer?
Characters in C# are UTF-16, so they are 2 bytes.
yeah, just running into those editor issues. not entirely sure how to set up property drawers so i'll start figuring that out and see if the system is working
ty for your help ❤️
@rich fog sorry to be a bother but do you know how to use the logic in my PassageHandlerEditor in a property drawer? im suuuper out of my depth rn with editor tools and im just creating a bunch of errors
i'm not sure exactly how to reimplement the logic in your thing but i can share this example property drawer i made for a very simple ranged float struct https://gist.github.com/phosphoer/565d78b3c6b55a4954ea97bc01e38bb4
Just create 1 scriptable object instance to hold serialized data on the disk, then it suppose to have list with entries which contains the scene, possibble passages and what scene the other passages reffer to on enter, it can be list of objects, or data which can be recreated to dictionary on deserialize or simply on Awake of SO instance. Its up to you. Double Dictionary would be good key:scene -> key: passage -> value: sceneKey
Dont forget to set dirty the SO instance asset and save it when edited
Does unity just not have the font to draw these icons? It keeps outputting empty
what icons?
I'm assuming this is gonna spit out some really weird looking characters
as it's raw number data converted to raw text data
they likely aren't printable ascii characters
I mean yeah converting random binary data to text is a crapshoot
I want to know if it's working though
you're better off printing it as hexadecimal or something
can you look in debugger?
hex is much more compact than binary
in terms of reading binary data on a screen
Hex:
FF
Binary:
11111111
Well this is taking the data that FF would mean and converting it to what character the data FF would point to
If I read the docs correctly
yes sure, which, if it's not encoded text in the first place, is very unlikely to be anything readable or have visible characters in a text encoding.
not to mention glyphs in whatever font you're using
it's just for saving data, not for displaying anything
right, we're just saying that displaying the raw bytes as a string in inspector is likely not going to be helpful for seeing what you want to see
Sure but you're doing Debug.Log
which displays text
would be easier to look at the value in debugger or convert to some other format to view it
What's the debugger?
most code editors will have some form of debugger that lets you step through code line by line and inspect the values of variables
If you are using a text-based format, you cannot write arbitrary binary data into it
(e.g. JSON)
Imagine if you could pause your code on any given line of code and check what all the variables values are at that moment and step through it line by line as it runs.
you can place a breakpoint at the point in code you wish to debug and execution will pause there so you can inspect things
oh ok, I'll just scrap the idea then
or make a hexadecimal converter
two unrelated ideas
well
I guess one of them is "do nothing" :p
You can write out hexadecimal (4 bits per characeter) or base64 (6 bits per character)
you don't need to make one, C# has it for you already
oh good
I'm just trying to the same amount of data into fewer characters
you can feel free to write your raw binary data to a file
this would be for reading it in Debug.Log or something
If you're using a text-based format, base64 encoding will be pretty good. It inflates the size of your data by about 33% (8 bits to store a single character which encodes 6 bits of information)
Yeah I'm using Json so that should help
im still confused why 1: you aren't just using system.guid, and 2: why not just store the custom guid as a string if the target format is json anyway
Unity can't serialize System.Guid
just ToString() it
You can do that, yes, but that requires you to reconstruct a guid from the string when you need it. It's nice to have a GUID type that is actually serialized by Unity.
I've implemented something very close to what Seboops is working on right now.
for my save system i use GUIDs for player photos, i just store the guid in the xml data directly which the c# serializer handles fine
if you're using the specific unity json serializer maybe that is not supported but any normal serializer should handle it fine
in my case, I need to store GUIDs in my ScriptableObject assets
Seboops is storing GUIDs in prefabs (which I've also done)
in both cases, the type must be compatible with Unity's serialization system
hence a custom GUID type
makes sense, i still don't see why not just store as a string in those cases, unless its some kind of highly perf conscious area
would make all this work out of box instead of looking for weird custom solutions
guid has a built in construct from string
You'd have to turn the string back into a GUID, either in some kind of "Init" method (gross) or every single time you use it
I guess you could lazily construct it and then hang on to that object
guid is a struct so it doesn't really matter how often you construct it, it's all on the stack
sure, but it's more of a hassle to have to construct it instead of just..accessing a field
make a property 😄
now I have to declare a property and a field
and now we're doing string parsing every time I access that property
you can absolutely avoid making your own GUID type, but I've found it to be very convenient to just..do it
can cache it ofc, idk i just try to do the simplest stupidest thing possible and then refactor if it becomes a problem
seems like they're wasting a lot of time figuring out how to store this thing and storing a string is easy
otherwise you spend all your time figuring out how to serialize a compressed guid and not making game
I never said that trying to shove arbitrary bytes into a text file was a good idea (:
hence everyone else saying to just write out hex
yeah there's definitely multiple easier ways to approach what they're trying to do
just giving my quick easy solution, there's def many ways to avoid the issues described!
This is a lot of unexplored territory for me so I'm exploring it and trying to see what works and what doesn't, because I know that saving stuff in base 10 strings is inefficient. If I can learn how to save stuff more compactly, that can help me in the future, help me become a better programmer, and add to my computer experience.
frankly i would just ignore any worries about inefficiency for now until it works, it really probably won't matter, especially given that you're saving to json anyway
Yeah json is definitely not very efficient
for my game i save player photos to base64 and store that in an xml file which is massive and it literally does not matter at all, there's no point in worrying about whether your guids are 10 bytes or 100 bytes
(until you see that it has become a problem or you know for a fact that you'll have to store 100000 guids or whatever)
@rich fog I've added your RangedFloat and RangedFloatPropertyDrawer scripts to my project to see if i can get them show up when i click the "Add Passage" button. but...im not sure how to manually call for the float fields to be rendered.
with the PassageHandlers, i did it like this:
Editor tmpEditor = CreateEditor(handler.Passages[i]);
GUILayout.BeginVertical("box");
tmpEditor.OnInspectorGUI();
GUILayout.EndVertical();
what would be the equivalent for property drawers?
yes, it's not terribly important
Sorry I’m on my phone now and don’t know the api off the top of my head but I think it’d be however you serialize a “normal” value using the inspector gui api, so not using the CreateEditor method
ill take a look, thanks
-- Question moved to #archived-networking
It's possible to serialize it with a union struct (the layout of System.Guid is well-defined to be equivalent to Win32 GUID so it's okay to do that)
Terrifying
I'm not at my computer but I can write up an example soonish
I hadn't even considered recreating a union in C#
Well, technically you don't even need to do that if you don't want to
You can define a struct with the same layout and just serialize that
Then bitcast it to Guid when necessary
i.e. Unsafe.As or *(Guid*)&value
Should note Unity also has its own GUID struct which is different, it's four ints (similar to Unreal's FGuid)
System.Guid is specifically the Win32 GUID struct
Yeah
I'd have used that, but it's editor-only
I don't think that one is serializable anyway so there'd be no real point
Any reason why onAssetDeleted isn't being called?
I mean OnWillDestroyAsset
the doc page is super barebones, it doesn't even tell me the names of the parameters
OnWillCreateAsset runs just fine
[Serializable]
[StructLayout(LayoutKind.Explicit)]
public struct SerializableGuid
{
[FieldOffset(0x0)] public Guid Guid;
[FieldOffset(0x0)] public int A;
[FieldOffset(0x4)] public short B;
[FieldOffset(0x6)] public short C;
[FieldOffset(0x8)] public byte D;
[FieldOffset(0x9)] public byte E;
[FieldOffset(0xA)] public byte F;
[FieldOffset(0xB)] public byte G;
[FieldOffset(0xC)] public byte H;
[FieldOffset(0xD)] public byte I;
[FieldOffset(0xE)] public byte J;
[FieldOffset(0xF)] public byte K;
}
This would work too (the union version would just be defining a RawGuid struct at field offset 0 instead of having the fields in there directly)
but yeah System.Guid is guaranteed to have that layout
Is there a reason you haven't just used four ints?
Because that would break if the endianness changes
wouldn't fields A-C break in that case, then?
No because they'd be correctly byte-swapped
field A is the only one that would still work properly with the 4 int layout, since well, it's already an int lmao
I don't think it's supposed to be static.
Hmmm... Maybe it is.
If you use four ints then it'd swap B and C as a single 32-bit unit, and the 8 bytes at the end would also get swapped
Yeah
It's designed to match https://learn.microsoft.com/en-us/windows/win32/api/guiddef/ns-guiddef-guid
Which is why it's allowed to be used in interop
lmao
I actually prefer that layout, it makes formatting and a few other things easier
also matches the actual guid spec
right
The signature doesn't match the one in docs though. You need the RemoveAssetOptions param as well.
it's still not being run I also removed static
Did you try the exact signature with the second param? And it probably needs to be static after all.
yeah I tried with static as well
Also it's OnWillDeleteAsset. Not Destroy.
oh wait
I forgot to rename it
now it's working, thanks
this whole thing could've been avoided if intellisense was intellisensible enough
do any modern CPUs even use big endian?
I don't think this is something you need to truly worry about
Most platforms nowadays are little endian, but imo that's no reason to use the wrong layout
Hi friends, Is there any way to implement Stripe or PayPal withdraw/deposit into unity?
you can make your own server with an API calls
I would not recommend you put storing anything in a client / unity game
okay so there is no direct way to do this on unity right
What's wrong with using Stripe/Paypal sdks?
What platform is this for?
Android?
Stripe has web, android, etc. sdks
you would use those
Yes, android and ios but with unity
Unity runs on android and IOS. YOu would implement stripe as native android and iOS stuff and have that communicate with unity
there is also a dotnet library it seems, supports also NET Standard 2.0 (unity version)
https://github.com/stripe/stripe-dotnet
uses an account’s secret key, so I suppose its not totally unsafe
{
public NativeList<FixedString32Bytes> MyStrings;
}```
Should this struct work with JOBS and Burst? What would be an alternative?
native array
Rename it!!!
Hey everyone,
I have a fixed joystick (from the original joystick pack on the Asset Store) in my scene. In certain cases, I want to set the center of the joystick to the bottom center anchor of the joystick handle, which works fine. However, I want to clamp the joystick's movement so that the bottom center serves as the starting position and the top of the joystick as the ending position. Currently, after adjusting the anchors, the joystick's minimum position is below the bottom center, and the maximum position is at the center. Instead, I want the minimum to be the bottom center (starting point) and the maximum to be the top of the joystick.
Could anyone help with this?
i have attached the snippet which handles the case where im adjusting the anchor positions of the handle.
private void ChangeJoystickState(int idx)
{
Debug.Log("Callback: " + idx);
if (idx == 0 && controllerUIManager.yawAndThrustJoystick.AxisOptions == AxisOptions.Vertical)
{
// Normal mode - bottom center
Debug.Log("Normal mode");
thrustAndYawHandle.anchorMin = new Vector2(0.5f, 0);
thrustAndYawHandle.anchorMax = new Vector2(0.5f, 0);
thrustAndYawHandle.pivot = new Vector2(0.5f, 0);
thrustAndYawHandle.anchoredPosition = Vector2.zero;
}
else
{
// AltHold mode - middle center
Debug.Log("AltHold mode");
thrustAndYawHandle.anchorMin = new Vector2(0.5f, 0.5f);
thrustAndYawHandle.anchorMax = new Vector2(0.5f, 0.5f);
thrustAndYawHandle.pivot = new Vector2(0.5f, 0.5f);
thrustAndYawHandle.anchoredPosition = Vector2.zero;
}
}```
Oh god, this player controller script is morbidly broken...
At least, the moving platform motion detection is...
Should I post the script?
Did you want help or did you just want to vent about an issue you're facing?
The former. Definitely. I'm terrible with code, and my bro is burned out.
If it's the former, then yes. If it's the latter, then please stop posting off topic 😄
Okay, let me fish it out. I'm working with multiple different computers here.
I feel like detecting moving platforms should be easy but maybe I'm not thinking enough on what is required
Like, detect the platform the player stands on, check its velocity or movement, hook onto it
Okay, I'm pretty sure it's this one
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
https://hastebin.skyra.pw/lesohidara.csharp
How about this?
Anybody still up?
Everyone is waiting for you to ask an actual question.
half the world is up
Well, then my question is, how do I make the platform motion detection work right?
My bro insists that it can be fixed.
You'll need to elaborate on what you mean by that.
Well, what I want to do is make the player able to be moved by moving platforms or objects without using triggers for every single possible platform.
https://www.youtube.com/watch?v=2MkNoaWJWf4
So THIS is a definite no-go.
In 3 minutes set up a moving platform in your game. Works with Unity's Ridgidbody and Character Controller.
Demonstrated with Bolt(Visual Scripting)
Support this Channel: https://www.patreon.com/SmartPenguins
Discord: https://discord.gg/FPPJf5r
Facebook: https://www.facebook.com/SmartPenguinsIO
Twitter: https://twitter.com/SmartPenguinsIO
Inst...
What's wrong with that approach?
Well, if you want your character to be able to walk along moving rigidbodies, you're pretty much SOL.
Isn't that exactly what the video covers?
Note I haven't really watched the full video
No, it uses the aforementioned triggers for platforms.
But what's wrong with that
Why is that a definite no go
I can't have every single moving object have a trigger.
Why not?
🤔
Is it an authoring problem?
A performance problem?
What's the concern?
Because I'm almost certain that a better solution is possible.
If there was a way to check the motion of the object directly under the player, and apply said motions to the player, that would be ideal.
Well this is exactly one way to do that
But sure there are many approaches
Why don't you go look for some other tutorials?
There's also something like this
https://assetstore.unity.com/packages/tools/physics/kinematic-character-controller-99131?srsltid=AfmBOor2eLxcafBRs5kLH27sFyOMo7TgzlfmYddqkrnpMelUAgcgu87F
But that also uses a special component for each platform
In the end the platform is going to need something to let the player know it's a moving platform
Be it a component, a tag, etc
I think my bro and I should look into this...
Sometimes it's all a matter of knowing where to look, I guess.
You could raycast any time you hit the ground? Like PraetorBlue was getting at, there's so many ways to do this, and triggers aren't bad either since they're optimized through the physics engine anyway.
Basically, my idea is to use a raycast to detect the platform, and if the player is standing on said platform, the player will also be moved relative to their position in the platform’s space
And velocity would need to follow suit
That's how I'd approach it too
And I did have a prototype that did it.
https://x.com/newgameplus_ld/status/1466558649120088064?s=46&t=1A3JnRKz0mNHrDv4eDn76A
Dude, use fixupx.
https://fixupx.com/newgameplus_ld/status/1466558649120088064?s=46&t=1A3JnRKz0mNHrDv4eDn76A
@iwatanaomi @milkycartoon_JP
Flappin' Flippers! Another Pecola: Shooting Star prototype. This time, featuring (almost) fully functional moving platforms.
[Proceeds to miss the last platform]
Music is from Leander (Amiga)
#pecola #naomiiwata #iwatanaomi #fangame #madeinunity
Only question is, what did he and I do wrong in the code to make the character's movement go completely nuts?
It looks perfectly fine to me 👀 But then again I have no idea what's going on under the hood here.
Is it just normal Unity physics and a rigidbody player controller?
hi guys, since im bad at coding shaders im wondering if its good to animate some tree sway or similar things with a rig in the model and having it loop in the game. Is it heavy to run many animations. Lets say i have many trees each with a rig and the simple animation of the swaying
Yes, that's much heavier than using wind.
Well, the video my bro showed was from a while ago.
Up here is the video where things went wrong.
And it's based on Unity's Starter Third Person Character Controller. No rigidbodies there.
I completely missed this one, sorry.
Yeah I mean I'd highly recommend using a physics / rigidbody based character controller- otherwise you'll basically end up writing your own physics engine.
No prob. It got buried.
Well, we kinda tried that, and got plagued with problems.
I posted videos below this post detailing what problems we ran into.
So, at this point, my bro and I have 3 options from here.
1. Continue developing from the starter character controller.
2. Revive the Rigidbody-based controller.
3. Investigate that kinematic character controller.```
Or buy a feature complete controller on the asset store
Like that'll ever happen.
Like I said, the option is open for us to investigate it.
I'm also liking the dynamic gravity it's showcasing.
Either it's a game-changer, or we run into problems that are just too much...
The kinematic character controller is a rigidbody based character controller, afaik. And it is pretty neat so definitely do consider it.
Though I don't quite know if I like this part...
Ah, I'm mixing it up with some other asset ._.
I'd certainly like to know what else you have in mind.
Thats not so bad. We have a external velocity variable that gets added to during the frame and then gets resolved during the move phase
It looked so similar with the capsule screenshot,
https://assetstore.unity.com/packages/tools/physics/physics-character-controller-203438
My bro and I have a lot to investigate.
Thanks a million, peeps.
I really gotta sleemp now tho
Howdy folks! I'm working on decoupling and restructuring parts of my game, especially for the stuff involving character parts (e.g. the character itself, a spellbook they cast spells from, and the independently controlled object that the spells are spawned from).
Because it has local split-screen style multiplayer, I have an object that has information about the characters, including the InputActions that are used to control each character, which many of those parts reference. However, since that object also has lots of public information that those objects don't need to know (like the starting position of each character and their parts), I feel like there should be a better way to get the information about the InputActions to the other parts. Does anyone have some advice for how I could do this?
This isn't really about the input system and more about code structuring
I already have it functioning where each part can get their input action stuff, I'm just trying to make sure they don't have access to too much to keep things organized
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/accessibility-levels (+ [HideInInspector] and [SerializeField]) 
Perhaps you could just give the input actions to the characters, instead of having the characters explicitly look for it on this object
Maybe, it gets a bit messy with timing because I can't put it in start or else I end up with a race condition and the timing of when the info script gets the info about the character changes a bunch depending on if the game is in online or couch multiplayer
If it helps at all, this is a simplified version of how everything connects right now.
Will a Mesh defined like this actually draw anything?
I expect no, since it basically has no width
Mesh lineMesh = new Mesh();
lineMesh.vertices = new Vector3[]
{
new Vector3(0, 0, 0),
new Vector3(1, 1, 1),
};
lineMesh.SetIndices(new int[] { 0, 1 }, MeshTopology.Lines, 0);
hello
did you try running the code? (i haven't messed with meshes before, i may be missing something)
I wouldn't expect anything to appear.
Yeah, but I'm trying to draw it in a render pass so I'm unsure if I'm doing something wrong elsewhere.
You can write a shader that generates new geometry. I presume that's what "point" and "lines" modes are for
I see, so how can the shader tell which topology it uses?
I don't have much experience there, but I know that you can specify what kind of primitives you expect to receive in the geometry stage
When it starts up (either when its spawned or in OnNetworkSpawn) CharacterManager is given a ScriptableObject called CharacterInfo, which has the input actions, equipped spells, and starting locations each object for that character. The options I can think of are either splitting up CharacterInfo into multiple scripts, which are each held by different scripts (e.g. having a CharacterInputManager with a CharacterInputs scriptable object alongside scriptableobjects and scripts like EquippedSpells and CharacterPartsInfo), or instead trying to do what Fen suggested and having the CharacterManager directly give the information to the scripts. However, if there's a cleaner way to organize all this that would be great.
does anyone know how to display usernames in photon
#archived-networking has pins to Photon server discord
also very doubtful there is anything built in for usernames..
that usually comes from auth services, photon is not an auth service
hi guys
is possible to paint on an object, that have a material, and that painted area to be accessed later
like becoming a game object, and can be selected aand so on?
anything is possible
ok, so how can i make it possible?
its pretty diffcult to do I think
You have to paint then somehow track those points for another mesh
like extracting the painted zone a sub mesh of the initial one?
you define the painted zone with some points then use that as mesh no ? I have no idea what kinda game mechanic you're going for so its hard to say lol
im making a model viewer, when you can select a zone on the object (paint it), and then you can select it to add anotations, like info about that section of the object
One option would be to create a new mesh that includes all vertices that were painted over. The hard part here would be to decide which vertices to extract.
I guess you could paint onto a texture, then sample the texture at each vertex's UV coordinate
that would tell you which vertices to bring over
So, guys, its not really about coding but about github
its my first time using github and i followed this tutorial --> https://www.youtube.com/watch?v=pn1YgU81GUY
it worked well and all but suppose my project somehow got deleted or something, how or from where should i get it?
should i just you know, download it and Add it to projects folder?is that how yall do?Also, Everytime i make change, should i upload the project again?
How to Use GitHub With Unity (Also Works With Existing Projects)
Greetings, in this Unity and GitHub tutorial we shall be looking at how to setup a github repository with an existing unity project. The method to setup a github repo with an existing unity project is simple and I haven't seen it covered without the need to move files about, which...
Thank you!
You could always clone the project to your disk (under that green Code button you can get the link which you need for cloning) if you manage to remove it. When it comes to "uploading", if you mean commiting a changes (essentially saving) and pushing them to Github (moving the saved version to the cloud), you should do that quite often. That way if you for example removed some code that you think you need again or mess something up, you have the latest version available (you can even go back to any earlier commit you have made). Git allows for tons of cool features some of which may not be available on the Github Desktop app so if you for example want to recover something and you can't find the option on the app, you can always use the command line to do what you want (if you google anything related to git, you are likelier to find command line stuff than the desktop app tutorials)
Hello again. I'm trying to make it so that while my character is in the dash state they turn more like a car. I'm wanting to do this by utilizing RotateTowards(). Think Sonic boosting like in Frontiers as the best example that comes to mind. I've tried two different methods. One with the HandleRotation() methond on line 580. The other being the small region between lines 521 and 531. Neither seem to be working. It seems to still be the base movement turning just with the higher maximum speed.
https://hastebin.com/share/uposehuzax.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
I'm hoping I don't have to completely scrap my current player script.
Do you actually modify the turnSpeed when in the dash state? If it's high, it will be near instant.
You need to stop the player from using normal turning when in a dash!
I can't quite tell if you're doing that or not without reading closely
You might want to have a separate property for the turn speed specifically for dashing, that you use in your HandleRotation function too
Yeah, it's a lot to go through. I'm also assuming you're making sure you're not actually still using the normal rotation when calling HandleRotation (which is weirdly named if it's only for when dashing)
Fair. I kind of suspected that it was fighting with the normal rotation to begin with. Just kind of... struggling to decouple those. I'm going to try and make it so the logic in this line is only applied while in the normal "walk" state.
Thanks for the answer!
I see the link, And what will i do with it?I mean, where should i put it? Also,is the "Git" Reffered to the github web?
how would i go about spawning a game object directly next to another one, so that their edges are touching but not overlapping?
has anyone used MIConvexHull in terms of 3D Space?
grid snapping
o wait this isn't #💻┃unity-talk 
easiest way is probably still grids though
get the length of the object and then just translate the next objects position by that + whatever other position value
You need a clear definition for "touching"
It's tricky if the objects have complex shapes and arbitrary rotations
well here are my objects, no rotation and they are essentially rectangles save for the top part which i dont need to worry about for the snapping i want
Are these SpriteRenderers?
If these are axis-aligned, then you can just use the bounds property to figure out how large they are
And if they aren't, you can use localBounds to work out the size on one axis, then transform that into world-space
the parent gameobject has nothing other than just the transform component, the two children (the lighter color and the darker color) do indeed have SpriteRenderer components
its separated that way for animation purposes sorry if its confusing
localBounds will be the most generally reliable
Vector3 size = spriteRenderer.localBounds.size;
Vector3 worldSize = spriteRenderer.transform.TransformVector(size);
The resulting vector will tell you how big the renderer is along its right, up, and forward directions
Maybe it's a question for something like ChatGPT (lol), but I want to get a hint or point direction on how to achieve it.
I want to make a "State Machine-like" system, but without rigid predefined transitions in code. Something like this: entity in the scene has some types of components => it's constructing it's state transitions based on components' types => state machine controller gathers it's transitions and runs them on events call/Update.
How can I possibly achieve it without tight coupling my states into components/state creation duplication from them? I just don't like explicit transitions in code and want some modularity for it, so I don't care if states will be MonoBeh/ScriptableObject or plain C# object to achieve it. And I need this on NCPs/Player and not for only for AI like stuff. Mostly to avoid state flags and if-else chains for state management/animations (I'm not using Animator for my non-static entities).
Decoupling them seems to make my character move automatically and proceed to roll at their own whim. I will keep trying. Still we move.
Not sure what is the issue. Why cant you use an interface ?
you put it in git clone command but you don't actually need that if you use Github Desktop. It has a clone feature (File/Clone repository) that can clone straight from your Github without the link too, just select the repository you want to clone (cloning is basically same as loading the project. once you load your project, you don't need to do that again, there's different feature called pull if you want to "update" the existing project from the cloud). For the names of things: Git is a version control software that handles software versions for you (you can save your current stage of the project by doing commit and go back and forth between new and old versions of the project). Git itself has nothing to do with internet, it works on your computer and saves the project versions on the disk (don't worry it's very smart, it uses very little space). Github on the other hand is the web service that can save your Git projects on the cloud so you can easily work on your projects with other people or with different computers. Every time you do push, the changes (commits) you have done to your project since you pushed last time goes to the cloud (github) and are visible on the github.com web interface. Every time you do pull the changes that has been made to the project on the cloud (github) gets loaded to your own computer (Git). In general you should do commits quite often to keep the ability to get back in time if something breaks. You can do as many commits as you like before you push them to the cloud. If you only work on one computer, you don't technically need to ever push anything and you still get all the features of the version control (ability to go back in time etc.) but if your disk gets corrupted or your whole house burns down, you will lose your progress. If you only code on one computer (and you don't have others working on the same project), you never need to pull because you always have the latest version available on your Git.
@lapis otter So basically commit is something Git does (saves the current progress on your disk as a new version) and push (to cloud), pull (from cloud) and clone (new project from cloud) involves Github
guh, almost enough text to warrant a !.code
ok so i'm trying to work on an enemy state machine, and basically I have an "EnemyState" abstract class that I can use to store logic and whatnot, so it has an enter and exit function, and an update function
for example here's the idle state
and in the actual enemy script i'm making an instance of the states as objects so i can use the constructor to pass in data from the main enemy script
but i can't actually access anything from the state instances when i do it like this, am i doing smth wrong?
like it seems like I can't actually set "currentState" or anything
is your debug line in MuckIdle being printed?
yeah, the constructor line is being printed, but not the Enter() debug line
have you tried attaching vs to unity and walking through what happens?
i’m working in jetbrains rider rn unfortunately
hmm i see
it seems like the issue is calling functions from the object
you can use the debugger in rider
if the instance is “idleState” and i call idleState.Enter() that’s not doing anything
but it definitely exists since the constructor is being called
it seems from the code youve posted your never calling Enter
try calling Enter whenever you change the agents state
oo wait hang on i see now
yeah sorry, was abt to clarify
ChangeState calls the exit, changes the current state, then calls the new enter
and i’m calling ChangeState in start
this isnt the issue but this should be a call to ChangeState
have you used the debugger to actually inspect what is happening at runtime?
no, haven’t looked into that yet
i’m away for a bit so i can check that later though
what does the green squiggle say on (currentstate != null) if you hover over it?
i’m away so i can’t check rn unfortunately lol
that was just so i could call changestate without there being a currently selected state, i’d probably get rid of it though
I created a project in unity 2022.3 and updated it to 6000.0. I'm trying to do an initial build and it's giving me this error:
Is this a unity thing, or a messagepack thing? (I also am using MessagePack 3 which has a different process than messagepack 2)
(build target android)
So you have CMake 3.22.1?
I don't even know how the cmake dep got into the project tbh.. I installed nuget for unity, messagepack 3 and just tried an initial android build.. nothing special
I can't see anything in the messagepack and nugetforunity docs talking about cmake though
(I don't really know what cmake is yet)
It is, for c++. Usually you have cmake file associated with that.
hm.. where would i find out how that .. process? is getting kicked off
This page does mention CMake and specifically 3.22.1:
Note: Only Unity version 2023.2 supports CMake version 3.22.1. Unity versions 2022.3 and below do not support CMake.
it's just that dialog box which.. i can't copy and paste out of
yeah - I'm using unity 6000.0 (see title bar in background of screensnip)
I would start to look for .cmake file
What's wrong with the instructions shown in the dialog?
(Other than not being able to copy it)
Ah
i did upgrade the projec from 2022.3 - so something is getting left behind, but i don't know where the above is configured
this is the only file I see containing cmake in the project directory
i suppose i could rebuild the library.. I assume that would have happened as part of the upgrade process though
Whenever you upgrade you version, you should delete your library
ah! i found it.. the android tools paths didn't get updated
something in the android tools probably uses cmake
Yep, that worked.
Now - in the past I was doing builds using manually installed android tools. I seem to recall some bugs in this preferences dialog (like unity not respecting the SDK/NDK paths that you set).
Is unity 6's android pipeline all smooth sailing now? I installed the android modules from unity hub and .. it seems OK? But I don't quite recall why I had to do it manually for older versions of unity. It might have been a CICD thing (I use codemagic.io)?
does anyone know why unity would be throwing warnings as errors?
maybe this is just a unity quirk im not aware of but this is just a warning in rider, not a full blown error
but unity is requiring me to fix this to run
if that's a switch expression and not a switch statement it must completely handle all cases (or at least have the _ => fallback)
Iirc
I don't think that would result in a compile error though, it should throw a SwitchExpressionException at runtime for unhandled cases and it should just be a warning at compile time
do you perhaps have csc.rsp file in your assets folder that adds the -warnaserror+ compiler argument? or perhaps have that added in the additional compiler arguments in the player settings?
Maybe I've switched this to be an error? But imo it would mean the static analysis is much less useful if it wasn't an error
like what would it return; default?
I suppose you just said, it throws
that'd be awful 😛
I know that it defaulted to warning me about non-exhaustive handling of enums
yuck! lol
(which was anti-helpful, because slapping in a _ => ... case meant I could forget to handle a new enum value)
by non-exhaustive, I mean that it was possible for the enum value to actually be none of the named values
and this annoyed the compiler
You could consider moving these up; and silencing them via comment where necessary
can confirm that both rider and unity see this as just a warning by default
what version are you using?
Looks like I do have -warnaserror+ though, so never mind
this was on 6000.3.21 with rider 2024.3.3
i'd bet they have the same compiler argument and either forgot they added it, or was added by a team mate
lol that's stupid
i can't wait for unity to not be stuck on like .net 3
converting my library from .net 8 to work with unity is becoming a really annoying task
I don't have any compiler arguments added and have no clue what a csc.rsp is
try restarting the editor 🤷♂️
could just be a weird bug
already did but I gave up at this point
I shall wait patiently for unity 7
or whenever .net core will be used for unity
It's 100% on your end, I was wrong because I'm just used to working in projects with -warnaserror+ enabled
@odd arrow I'm assuming the problem is that the ARCore XR plugin includes an rsp file that's setting warnaserror for your entire project
I don't want to install the package just to see if that's the case.. but I bet it is
I can't math properly today.
I'm trying to make a system where I make arrows that point at things that are off-screen.
I got the logic down that decides whether something is on or off-screen. So now, I need to figure out the math to move a UI element in screen space such that it points to something in world space. Where I struggle is that I am unsure how to properly convert the world space position to screen space such that I can place the UI element. The rotation of ui element can come after.
This is my current approach and it moves the ui elements very little (and places them incorrectly too!)
pointers[index].SetActive(true);
Vector3 screenPoint = cam.WorldToScreenPoint(tile.transform.position);
if (screenPoint.x < borderSize) screenPoint.x = borderSize;
if (screenPoint.x >= Screen.width - borderSize) screenPoint.x = Screen.width - borderSize;
if (screenPoint.y < borderSize) screenPoint.y = borderSize;
if (screenPoint.y >= Screen.height - borderSize) screenPoint.y = Screen.height - borderSize;
RectTransform rectTransform = pointers[index].GetComponent<RectTransform>();
rectTransform.position = screenPoint;
rectTransform.localPosition = new Vector3(rectTransform.localPosition.x, rectTransform.localPosition.y, 0f);
I know the approach is simplistic, but I was trying to approach it one bit at a time
how would i initialize this dictionary of func's?
Do anonymous functions perhaps
If you want to pass a function as a delegate you do not use ()
() means to call the funciton
just use Clear alone
ive got a function i want it to link to also Clear alone doesnt work
Wouldn't it be () => Clear() ?
Please see this to see how dictionary initializer syntax works https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/how-to-initialize-a-dictionary-with-a-collection-initializer
no that introduces a pointless and unnecessary anonymous function in the middle
im trying to avoid putting it in awake is there a way to do it at compile time?
Here's an example: https://dotnetfiddle.net/qAqbhP
Test your C# code online with .NET Fiddle code editor.
Why
Only if the functions are static
you cannot access non static members in a field initializer, no matter what they are.
right i forgot about that
hey, i have this bit of code where im trying to switch between two cameras with a button press: https://pastebin.com/XmQy5cg7
the problem is that the camera is switch way too fast... is there a function in unity that would make the press more precise? i would like to have just this one button to switch the cameras rather than 2 buttons per camera. (the video is just me tapping the button btw)
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
You have an error in your logic here
(overheadCamera.enabled = true```
It's == to compare
You used = which is assignment
ik, i fixed this. it doesnt change the problem tho
Your other problem is you're using GetKey instead of GetKeyDown
i have a crash related to some unmanaged ecs code that only happens in standalone builds, and i'm trying to debug it, but after attaching visual studio to the standalone win64 player, visual studio catches the exception but then the standalone player somehow kills itself while the debugger is still attached and paused at an exception breakpoint
my hunch is that this has something to do with the default crash handler intercepting structured win32 exceptions and running a background crash handling thread/process or something that automatically kills the program, i wonder if there's a way to disable the crash handler?
in particular, visual studio is catching a managed NullReferenceException which is most likely actually an EXCEPTION_ACCESS_VIOLATION structured exception due to an invalid pointer access, that gets translated at the mono/native marshaling boundary
but i can't inspect the state properly because the thing just dies on me 😄
I'd check the vs options Debugging/general category. There are several options that could be relevant:
- break all processes
- break when exceptions cross managed/native boundaries
Also, maybe enable debugging all types of code in Debugging/Just-In-Time.
hmm good point, let me try those, thanks!
Also, how are you attaching to the build?
using the debug -> attach unity debugger menu from the visual studio unity extension
I find attaching via the attach to unity button obscures some threads. Try attaching to process instead.
ah yea that might also help
So my goal here is to create a tools Menu at the MenuItem level for my editor:
using UnityEngine;
public class EconomyCategoryEditor : MonoBehaviour
{
// Add a menu item named "Do Something" to MyMenu in the menu bar.
[MenuItem("MyMenu/Do Something")]
static void DoSomething()
{
Debug.Log("Doing Something...");
}
}```
Ain't working and google and Unitys Documentation says this is how this works. Even SearchLabAI thinks this is how it works, What am I doing wrong?
and it wont let me inherit : Editor either
just want to make my scriptable objects easier to make, and a tools menu at the top is way better than the default CreateAssetMenu way
are you using asmdefs in your project? because if so you'll need to make sure you're referencing the editor assembly if you intend to use editor code. but also you need to make sure that your editor code is not in an assembly included in the build
Im not, its literally a new project with zero imports or cusomtiztions
Do you ahave an error in Unity, or just in VS?
Assets\EconSim\EconomyCategoryEditor.cs(8,1): error CS1519: Invalid token '}' in class, record, struct, or interface member declaration
seems loike. basic syntax error
which is rediculous because there nothing wrong with my class
📃 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.
yeah, which i pasted above
line 8 is cut off
line 8 is not visible
as is everything above it
using System.Collections;
[CustomEditor(typeof(EconomyCategory))]
public class EconomyCategoryEditor : Editor
{
[MenuItem("Tools/Economy Engine/New Category")] // Creates a menu item under "Edit > My Custom Menu > Do Something"
}```
Thats the code
so the comment above that doesn't exist?
No there's 8 lines above that
show the full script
Wait also
{
[MenuItem("Tools/Economy Engine/New Category")] // Creates a menu item under "Edit > My Custom Menu > Do Something"
}1```
whwere's the function?
MenuItem needs to go on an actual function
This doesn't even match the screenshot
My scrrenshot was the same thing just stuff commented out, I removed all that
you have a floating attribute without a method it's attached to
In this screenshot it was actually attached to a static method, which is correct
This is very different from what you shared here
(but this one also has 8 lines not showing above it)
ok lets say i throw all my stuff away, how do i make a Tools/EconomyEngine/New Category for scriptable objects
MenuItem
I know i need to use CustomEditor
set the type; which is
Just follow the example code here https://docs.unity3d.com/6000.0/Documentation/ScriptReference/MenuItem.html
You don't need CustomEditor for MenuItem
MenuItem only needs a static method, in any class
i tried that and it didnt work
It works fine for everyone
show what you tried
and what went wrong
There are examples here https://docs.unity3d.com/6000.0/Documentation/ScriptReference/MenuItem.html
(it should of course only be in an editor script since it uses the UnityEditor namespace.)
And what's the error here?
Can you show your unity console
when you save that code
(and tell us which file this is)
note the yellow here means the file is not saved yet
so it's fine
so apparently that worked but i still have the red line
it's just VS acting up
Go regenerate project files
from the preferences -> external tools menu in unity
So how do I make this work then:
[CustomEditor(typeof(MyScriptableData))]
public class MyScriptableDataEditor : Editor
{
// No additional code needed here as the CreateAssetMenu attribute handles the creation of new assets
}```
Becuase this was what i was trying to do
i just wanted it at the top instead of the CreateAssetMenu
and what is the error when you do that
make what work exactly....?
I want a Tools Menu at the top of my editor lets me click the Button and it creates the ScriptableObject that iv already got defined
If you wasnt a menuitem to create an asset you would use the menuitem attribute and write code that creates one
A custom editor. class is for drawing the inspector in a custom way. it wouldn't be related
is it impossible to just add the MenuItem stuff abive this?
[CreateAssetMenu(fileName = "Item", menuName = "Tools/EconomySim/Item")]
or does Unity block that
On an editor class?
what would you expect that to do?
a custom editor is not an asset
Thats the autogenerated start to a scriptableObject class.
you're jumping around
thought we were talking about this class
which is a custom editor
not an SO
In any case i figured it out. ```
using UnityEngine;
using UnityEditor;
[CreateAssetMenu(fileName = "Category", menuName = "Tools/EconomySim/Category")]
public class EconomyCategory : ScriptableObject
{
[MenuItem("MyMenu/test")]
static void test()
{ }```
this DOES work
just throws that fake error now
so it accomplishs what i wanted
because thats what all the examples showed
All i wanted was a button in a menu at the top to make the SO.
this won't do that
As it is right now, no. But at least its where i wanted it now
now i can figure out the code to make that new SO
I appreciate your assist. Some items in the docs really dont make sense when put in the hands of someone learning them
i never would have used static for example. didnt even know that was required
it does say it right in the second sentence
The MenuItem attribute turns any static function into a menu command. Only static functions can use the MenuItem attribute.
I see that now
Iv seen other pages where that was written in the //statements so you wont miss it.
Kinda expected that
hence my skim missed it. I submitted feedback. Important things should be stated more than once :)
https://assetstore.unity.com/packages/tools/physics/kinematic-character-controller-99131?srsltid=AfmBOor2eLxcafBRs5kLH27sFyOMo7TgzlfmYddqkrnpMelUAgcgu87F
Finally got around to experimenting with this.
Does it have any form of controller support?
(I'm using a PS4 controller on a mac.)
Ok, it uses InputManager. Mystery solved there.
is there a way to declare the duration variable as public and use it inside the waitForSecond?
Sure. You'll need to create a new instance of WaitForSeconds in a method/property scope though.
do you mean new waitforSecond() inside a enumerator? i want to avoid using this new() as it creates garbage as far as i know
But you are actually creating at least one instance, as you want it to be dynamic with your dynamic float
the float won't change in runtime, it will be set from the very start...i just want that to be exposed and editable on the inspector so that i don't have to edit it in the IDE each time I think it should change. is there a way?
public float waitDuration;
private WaitForSeconds wait;
void Awake()
{
wait = new WaitForSeconds(waitDuration);
}
As dlich said and Nitku wrote, you need to set it at least once. Its not in the constructor but in a start method.
i got it now...thank you, i couldn't get what dlitch said back then properly, my bad
thanks @cosmic rain @mellow sigil
#🤯┃augmented-reality is your place to ask for
has anyone ever made modding support for lua scripting for unity? is there a lua to c# compiler for unity?
Like this? https://www.moonsharp.org/
thanks i’ll check it out
The examples use input manager you are free to use the new input system with it as well.
So, outside the recorder, it looks like the character is flickering between Idle and Walking.
My bro and I are having trouble implementing animations in the Kinematic Character Conroller thingy.
@arctic sparrow , could you copy-paste the script used to handle animation?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using KinematicCharacterController;
using KinematicCharacterController.Examples;
public class ExampleCharacterAnimator : MonoBehaviour
{
public ExampleCharacterController chara;
public Animator anim;
public Vector3 posDiff;
// Update is called once per frame
void Update()
{
anim.SetFloat("Speed", (transform.position-posDiff).magnitude*Time.deltaTime*60*60);
anim.SetBool("Grounded", chara.Motor.GroundingStatus.IsStableOnGround);
posDiff = transform.position;
}
}
You'll need to look at what's going on in your animator at runtime
What should I look for?
What state the animator is in and how it updates.
The big problem with this is that there are values that are pretty obfuscated by the code structure that we can't access with the animator script. And it seems that the position delta I'm trying to calculate is quite badly borked
anim.SetFloat("Speed", (transform.position-posDiff).magnitude/Time.deltaTime);```
Tried changing a portion to this...
No visible difference.
ok this might sound a bit cursed but I promise I have a reason for this
I have a MyClass<T> : BaseClass<T> where T : SomeOtherClass
how can I give the T in MyClass<T> a default value, but things that derive from MyClass<T> can specify their own T, where T : SomeOtherClass?
the point is I have a subset of classes that derive from BaseClass<T> with different Ts, that I want to be able to all store together in a list, hence the MyClass<T>
What does the animator window show?
Also that speed will result in almost nothing.
Lets say you moved 0.01 units in a frame, and you multiply that with deltatime ~0.00167777 your speed will be almost nothing.
Speed Numbers are fluctuating wildly between a small amount and double digit values
Ah, your dividing instead of multiplying in the other code block, nevermind then.
Well, multiplying in that code block made no visual difference.
Hi, im completely new to Unity and I'm having some trouble. Can anyone help me out with setting up ML-Agents? i have followed a turorial, and I can manage to run the premade examples, even training an example, wit the correct output, however when I was trying to write my own csharp scripts, it just doesn't recognize definitions used by the ml agents package even tho it is installed.
Assets\ML-Agents\Examples\Intro\Scripts\MoveToGoalAgent.cs(8,38): error CS0246: The type or namespace name 'ActionBuffers' could not be found (are you missing a using directive or an assembly reference?)
Read the error message and the docs
https://docs.unity3d.com/Packages/com.unity.ml-agents@2.0/api/Unity.MLAgents.Actuators.ActionBuffers.html
Well, that doesnt really help, as its not a programmatical issue, its rather the proper modules not being loaded into the project somehow. As my script is just me calling the method, nothing else
post your !code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
using UnityEngine;
using Unity.MLAgents;
using Unity.MLAgents.Actuators;
public class MoveToGoalAgent : Agent
{
public override void OnActionReceived(ActionBuffers actions)
{
//dostuff
}
}
I really don't know what to do to fix this.
screenshot your IDE window for this code
so first 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
I've followed the instructions, somehow I didnt even have that package, and not even linked it. Thank you so much for your help!
Is anybody still here?
I'm completely stumped with this.
Just to be sure, have you checked to make sure the running animation is set to looping?
It is
Does this server do code review?
if you mean dumping all your code here for a free review, I don't think so. If you have a specific concern in mind or want to find a better way to implement something, we might be able to help.
Post it in a thread here. Maybe someone might have time to look at it.
Having specific questions about it would help.
Don’t underestimate the willingness of some of us to procrastinate from our own work to comment on someone else’s 😅
rofl
True actually. I should have been studying the whole day yesterday and I ended up fighting over a stupid mesh generation question the whole day
Respawning Player
I feel personally offended
Though to be fair, today has been quite a productive day for me
I resemble that remark
haha, Yeah I have not worked on my unity project in a while 😅
Unity plz fix this and respond to my bug report 😦
looks like you upset unity lol
a few projects are cursed by this, i filed a bug report with some information about hung threads but no response ever
did you do any due diligence on your own computer?
a colleague gets it too from the same projects too
I'll take that as a no then
huh, its not my pc but certain projects but i havent had time to weed out the specific thing
i'll stare at code all day just to change a few lines. gotta keep working on that picture-perfect script . . .
[field :SerializeField] public string Name { get; set; }
how to bind this property to label/textfield.value?
wdym by "bind it"?
make an actual custom property that does it
public string Name {
get => myTextField.text;
set => myTextField.text = value;
}```
Not an auto-implemented property
want to bind this property to custom editor in ui toolkit
Makes sense :) Try #🧰┃ui-toolkit
already posted their
then do not cross post
ok
is there a function to minimize the unity game window(on build)? i cant find the windows button in KeyCode somehow
I doubt it as API is mostly generic for all platforms. You could import windows API dlls though and add something
I hate to say "ask a chatbot" but they are unfortunately very useful for this
it helps to read the docs
Hey all, hopefully quick question. Making a pixel art game and I've got everything looking crisp, except my UI coordinates do not conform to my reference resolution. Like I have a super ultrawide monitor, and while the viewport is 1920x1080, the UI is waaaay off on the edge of the screen. I mean technically the UI elements are positioned correctly, but the area of the UI is matching my resolution vs. my reference resolution. I figure there is a coding solution to this yah?
No this is a #📲┃ui-ux problem and it has to do with how you anchored your UI elements and your canvas scaler.
Evening. I'm doing simple Graphics Raycasting. It seems for the first frame, no objects are detected. Subsequent frames, objects are detected fine. Event system is assigned in Inspector and never disabled. Here's my code:
Debug.Log($"Casting at {touchInfo[touchIndex].position}...");
pointerEventData = new PointerEventData(eventSystem);
pointerEventData.position = touchInfo[touchIndex].position;
List<RaycastResult> rayResults = new List<RaycastResult>();
graphicsRaycaster.Raycast(pointerEventData, rayResults);
Debug.Log($"Casting hit {rayResults.Count} objects");
I've attached a shot of the Scene
I can't figure out if there's a built in way to do this, but is it possible for a selected object to change the value of the scrollbar based on where it is in the box? Basically i want the currently selected button to move the scrollbar down.
You can tell the scroller to move to a specific spot, yeah
let me go find the script I mashed together for that...
how does GPU instancing works on materials? Lets say i have one single material on 2 gameobject prefabs, then i instantiate the first prefab 10 times, then the second prefab 10 times. Does the gpu instancing on this single material manage the multiple instances of the 2 prefabs?
I'm using UI extensions if that helps!
oh man this is a little goofy
a powerful website for storing and sharing text and code snippets. completely free and open source.
the first class is used to snap a scroll rect to itself when its object becomes selected
the second class does the actual movement
wow amazing! let me take a look, thank you! 🙂
It figures out the local-space difference between the content and item RectTransforms
it uses that to set the content's position
lines 21-26 prevent it from going too far
you can immediately ask for the normalized position of the ScrollRect after moving its content
I'm pretty sure I cobbled the second class together from a forum post
since it's particularly..janky looking
so would this run on every button? When it either selects or deselects?
The core idea is that you need to move the content rect so that the item of interest winds up on screen
I attach a ScrollRectSnapper to every selectable thing in my UI, I believe
or at least a sizable portion of all selectable things!
in my case they're all buttons for rebinding so it should be simple!
don't remind me that I still need to do rebinding 
is there any way i can have a navmesh agent go to a destination indirectly? like have it go in an arc, or move in the "general" direction of a destination if that makes sense
NavMeshAgent will always take the shortest path it can calculate. if you want it to go in some other path, you'll need to tell it to go to those various points in sequence to create your shape.
What is the reason why you want it not to go the shortest path?
working on kinda "skiddish" enemy AI so I'm seeing if I can give it some characteristic by not necessarily bee-lining it to the target
you can create your own path or modify a generated one and just tell the agent to use that
gotcha, thanks
good trick would be to take 4 points from a generated path, feed those into a Bezier Curve generator and then feed that back into the agent path
oooo yeah i didn't consder that, thanks!
As far as I understand it, yes but its not the material thats doing any managing: https://docs.unity3d.com/Manual/GPUInstancing.html - rather, a copy of the mesh is created and the same 1 material is applied to that mesh, in a single frame all 20 of the meshes using that 1 material will be drawn - what might not be clear is for meshes that use multiple materials where some might not be GPU instanced, I imagine you lose all benefit of GPU instancing as youd have to have multiple copies of the mesh being drawn for the non GPU instanced + 1 for the GPU instanced version, but thats just a guess
i understand that. But what if i apply the material to two different meshes and i have 10x of one gameobject with that mesh and 10x of the other mesh? its still works as intended?
or its better to have a material for each different mesh(gameobjects) ?
I would expect the two meshes to be rendered separately, no matter what's going on with the materials
I would expect there to be two draw calls.
Each would render every instance of a single mesh
yes, i hope its this way then!
In doubt, you should be able to check the Frame Debugger at runtime as well, and see how many instances are created
My artist sent me an asset that's rendering the transparency more in-game.. Why? Here's the screenshot from her:
(the asset pasted over a game screenshot)
and here's the shot in-game (with the same asset)
(it's almost completely see through in-game)
why is unity normalizing my input automatically with the new input system?
its set to analog
only happens on controler
on keyboard it returns -1 1 if you hold w and a at the same time
but for controllers its returning -0.7 and 1
because you weirdly made a composite instead of just binding the joystick directly
delete that binding and just bind Left Stick directly
as a normal binding
Er i think I did that already too and the composite was my attempt to bypass the auto normalizing
Maybe #💻┃unity-talk could provide more insight, though what are your settings on the image rendering it, and the import for the asset itself? Any alpha you may have changed or something?
it doesn't auto normalize things by default
make sure you don't have any processors on the Action
(can you show a screenshot of the action configuration?)
no alpha changes
Also this is really an #🖱️┃input-system question not a code question
oh shit i didn''t realize that was a section ill send that screenshot in the input section
Hmm, my only other guess would be post processing affecting the layer, though id imagine that would make it less transparent - next suggestion would be to test in a blank scene and see if the effect is the same, if it is, something odd might be happening with the source image, and if not, something odd may be happening in your scene instead
post processing could be it - i've got a post processor but I don't think i've mucked with anything that would affect this
i didn't think post processing affected UI elements
Normally it shouldnt, but you can setup layers that affect your UI or may have changed the layer your UI is on or something
Actually this is completely normal and expected. This means it's NOT being normalized
Sounds like you want to clamp the magnitude
I want it to return -1 -1 when I go 45 degrees between forward and left
That's not really how circles work
https://www.reddit.com/r/Unity3D/comments/z2jtks/why_alpha_blending_is_so_different_in_unity_and/
My color space is set to linear - so I'm trying setting it to gamma and seeing. 🤷♂️
that is how analog sticks have worked since ps2 days on every game engine ive ever tinkered with
Why do you think games had weird bugs like walking faster diagonally
because they were not normalizing the vector after gathering the input
Normalizing is wrong
analog sticks are still supposed to return a value between -1 and 1
in all directions
Clamping magnitude is correct
Not in my experience. But you may get that with the composite
The thing is at 45 degrees it's not actuated fully left or right
It's giving you accurate data
alright so here is my problem I have a blend tree that handles all my locomotion
with keybord and mouse
its returning -1,1 if i hold w a
with controller -0.7, 0.7
You should clamp the magnitude so you get the same with both
inputVec = Vector2.ClampMagnitude(inputVec, 1);
yeah, alpha blending is a Whole Thing
yep .. i'm going down the rabbit hole right now
i'm not quite sure what color space our artist uses
but as far as I can tell .. my project is in linear space and their work is too so these should be similar looking
but if the supplied vector2 is different on each device isn't it going to just return 2 different values
No
You'll get that exact.707 thing with the keyboard as well if you clamp the magnitude
The thing is the keyboard is not exactly a 1-1 analog for an analog stick. They work slightly differently. An analog stick is a circular space.
The keyboard is sort of simulating a square
ClampMagnitude limits the length of the vector. [-1,1] has a length of around 1.41. [-0.7, 0.7] has a length of 1
ok yhou're right
now both devices returning the same value
thank you
now i gotta remake my blend tree tho 😦
You can quickly update everything by pasting this into the fields that need changing:
* 0.70710678118
You need to change the diagonal ones
Unity can do basic math in fields
3 * 0.5 becomes 1.5
so 3 * 0.70710678118 will wind up being some weird number that's had the correction applied
OK great I was able to get all this working correctly now thanks for your help
You can even input R(-1, 1) to a float field to randomize it. Handy if you want to randomize some values on a bunch of objects at once
I always forget it exists tho
I'm experimenting with a custom render pass.
From the Execute method is there a way to check if this is the last execution of Execute for the frame?
i.e. if I have more than one camera, I just need to know inside Execute that this is the last execution for the last camera
Hey all, back with this problem again:
Here is code for moving an object to a relative 3 dimensional position and rotation, which is the value read from actions["Position"] and actions["Rotation"] respectively. (I need to do this by setting it's velocity, this is the intended way)
These are called in a FixedUpdate() function:
private void MoveToController()
{
Vector3 targetPosition = actions["Position"].ReadValue<Vector3>() + followTarget.position + followTarget.TransformDirection(offset);
Vector3 direction = targetPosition - rb.position;
Vector3 velocity = direction * FOLLOW_SPEED;
rb.linearVelocity = velocity;
}
private void RotateToController()
{
Quaternion targetRotation = followTarget.rotation * actions["Rotation"].ReadValue<Quaternion>();
Quaternion deltaRotation = targetRotation * Quaternion.Inverse(rb.rotation);
deltaRotation.ToAngleAxis(out float angle, out Vector3 axis);
Vector3 velocity = angle * FOLLOW_SPEED * Mathf.Deg2Rad * axis;
rb.angularVelocity = velocity;
}
followTarget is the world space vector for my target position, and this is currently set to be the camera's location (the offset variable just puts it infront of the camera).
My character can move around and rotate with all 6DoF, and as my character is cylindrical (with the camera attached at eye level), when rotating the camera's position will also change.
My code mostly works. When i try and move around without rotation, my object tracks to where it's supposed to be perfectly fine, however the issue occurs when rotating, my object just stays where it is, and doesn't follow my rotation with me, and no matter what i've tried, i can't figure out a working solution that accounts for this. Does anyone know what Im doing wrong? The attached video is a demonstration of the problem. (The video looks off centered due to it showing my left eye, but it's not when using a headset)
Im about to begin work on programming a weapon system, I was thinking about using a composition instead of inheritance approach for this.I was thinking id have an enum with the WeaponType { melee, pistol rilfe etc, and have a weapon scriptable object that would hold all individual weapon data then a weapon manager script that would have a switch statement that would execute different logic based on the type of weapon the user is holding. Thoughts on this?
a switch statement for the differing weapon logic implementation isn't great, you ideally want an interface/virtual/abstract function that is implemented or overwritten by each weapon type.
The weapon manager then just needs the instances and calls the functions to do stuff.
Then all the weapon logic is split up into multiple different places
and its hard to debug and edit
thats the point, instead of a switch statement that gets crazy large when you have 20+ weapons you have a set of classes that hopefully share some common logic (e.g. item -> weapon -> gun)
It's fine if you do not have too many varieties
hmm I see what you mean but then it can get so complex item -> weapon -> gun -> pistol , then weapon->gun->SMG , weapon->gun-> shotgun etc etc
it is more complex but also good in many ways. E.g. both the pistol and shotgun can share the gun logic which can be made more flexibly (they can override fire rate, bullet count, spread ect)
then adding a new gun later is nice and easy as you did the work already
I can do that with my approach as well just using a generic weapon scriptable object
ima make a small sample with both and see how the code actually winds up
How many guns will you have?
25 or so
SO or not yea up to you. I still encourage the use of good OO programming