#archived-code-general

1 messages · Page 405 of 1

wintry crescent
#

I still need some way to open those settings from a button, through uiManager

#

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

heady iris
#

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

heady iris
wintry crescent
heady iris
wintry crescent
#

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

heady iris
#

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

wintry crescent
#

I mean

#

a compile-time check that I'm not passing in junk

#

that will only get discovered at runtime

heady iris
#

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

heady iris
#

The compiler can't reason about that

wintry crescent
chilly surge
#

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?

rotund perch
#

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

heady iris
#

there's a 50-50 shot on it overflowing :p

#

Are you trying to get a uniformly random unsigned integer?

rotund perch
#

Yeah

#

Maybe I can add two uniformly random positive integers?

heady iris
#

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

rotund perch
#

Oh right

heady iris
#
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

heady iris
#

it excludes the maximum possible integer value

#

If I needed to avoid that, I would use System.Random instead

chilly surge
#

(Do you really need the full range though, what are you using it for?)

heady iris
#

indeed -- is this going to be an RNG seed or something?

rotund perch
#

I'm trying to simulate GUID.NewGuid();

#

so just setting each of the 4 values to a random uint

quick token
rotund perch
#

uints don't have negatives

#

so if it were negative it would probably not work but I'm not sure

quick token
#

oh

#

cant you just replace int.MinValue with 0 and int.MaxValue with (int)uint.MaxValue

rotund perch
#

No because uints go twice as high as ints

rigid sedge
#

This isn’t related to coding but I can edit a line on pro builder

rotund perch
quick token
chilly surge
somber nacelle
rotund perch
#

That’s something I’ve only heard about

#

Never done it personally

somber nacelle
#

just use System.Random to randomly generate the bytes ez

young tapir
#

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.

rotund perch
quick token
rotund perch
#

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

quick token
#

huh, damn, i guess i really need to brush up on my maths skills then lol

rotund perch
#

I had the same idea until he pointed that out

#

I had forgotten about two dice being not uniform

quick token
heady iris
#

You can generate as many random bytes as you want

#

(similar ideas)

somber nacelle
#

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

heady iris
leaden ice
#

sorry real life got in the way but it seems like you found some path forward

heady iris
#

if you wrap that in a checked block, it throws up

heady iris
young tapir
marble glade
#

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?

leaden ice
marble glade
#

no

spare dome
leaden ice
# marble glade no

Show the inspectors of the two objects that are touching that you expect to cause this code to run

steady bobcat
#

script needs to be on same game object to get trigger events btw

marble glade
#

Im using another gameobject with the manager

leaden ice
# marble glade is this two colliders

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.

marble glade
#

they are the same

leaden ice
#

so there is nothing to trigger

#

so I don't understand what your question is about

spare dome
#

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

leaden ice
#

The manager script is not present on either of these objects so it's completely irrelevant

marble glade
leaden ice
#

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

marble glade
leaden ice
#

Do you understand?

marble glade
#

Yes

#

so its better if I use the start collider to start the challenge?

leaden ice
#

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

marble glade
#

ok

lucid brook
#

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.

leaden ice
#

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;

lucid brook
#

I'm not that bright when it comes to math stuff lol. thank you!!

heady iris
#

annoyingly, there isn't a Mathf.Remap function built-in

#

inverse-lerping and then lerping with the result is very useful

steady bobcat
#

A lerp is min + ((max - min) * lerp) so you can think how you can replicate the inverse

heady iris
#

oh yeah, it's easy to implement

#

it's just not there

#

like transform.left

steady bobcat
#

ha yea it would be convenient if it was just there 😄

heady iris
#

(c'mon, maybe in Unity 7..?)

rotund perch
#

oops that clamp vector function is messed up

heady iris
#

woops

#

Any clue why Rider thinks the first method is a Unity event handler?

#

I don't see a unity message called "Observe" anywhere

empty elm
#

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?

leaden ice
heady iris
#

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)

leaden ice
#

Generally if you find yourself trying to serialize a Unity asset to JSON there's something wrong somewhere in your design.

heady iris
#

(perhaps you want to serialize an identifier!)

#

well...a stable identifier

leaden ice
empty elm
heady iris
#

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

empty elm
#

Maybe I should save the string id of the items, and have some class that references all Item SO and deserialize that way

leaden ice
# empty elm yes exactly

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
leaden ice
empty elm
#

Perfect, thanks!

rotund perch
#

funny how this same problem has come up so many times

#

well only once since me

#

but it's weird that it happened twice

leaden ice
#

It's a super common use case

rotund perch
#

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

rotund perch
#

oh yeah I found that then forgot it existed, thanks

rotund perch
#

alright here's my code.

#

pandora's box has been opened

rotund perch
#

alright it's still happening

#

I'm guessing it's actually the prefab logic being messed up, not the guid logic

heady iris
#

what is "it" here?

rotund perch
#

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

heady iris
#

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 (:

rotund perch
#

I mean... I put [Serializable] here but I don't know if that actually means it's being serialized right

heady iris
#

None of these internal values are serialized.

#

They aren't public and haven't been marked with [SerializeField]

rotund perch
#

ohhh

heady iris
#

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

rotund perch
#

like this?

heady iris
#

sure, that'll tell Unity it should be serializing all four of the uint fields

rotund perch
#

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

heady iris
#

it's a serialization library

cold parrot
rotund perch
#

this is a custom guid

cold parrot
#

what does that change?

rotund perch
#

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?

rich fog
#

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

tepid charm
#

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

rich fog
#

oops sorry i mistyped, yes 32 bits

#

anyway the difference is negligble anyway but i think that was their meaning

cosmic rain
tepid charm
cosmic rain
tepid charm
#

just a skinned mesh yeah

#

also how does that work with LODs?

#

mesh LODs I mean

rich fog
tepid charm
#

but I need them

rich fog
#

what i mean is, what are they being used for?

tepid charm
#

to animate soldiers

rich fog
#

can you disable them entirely at some distance vs updating every few frames?

cosmic rain
#

1000 animated characters is not really realistic with gameObjects. You'd probably need to go into DOTS/ECS

rich fog
#

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

tepid charm
#

tried it before

cosmic rain
#

Well, it's that or some custom smartass lod system that simplifies the animation setup.

rich fog
#

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'

cosmic rain
#

Or animated billboards

tepid charm
#

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

rich fog
#

if this is an RTS maybe you could prerender a few angles of animation of the soldiers and use those on the billboards

rotund perch
#

just do this for each character?

tepid charm
#

that's what total war games do and it works well

rich fog
tepid charm
#

also lol, nice UI

rotund perch
rich fog
cosmic rain
sly shoal
#

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
rotund perch
#

this should fully compress it

#

without doing any actual algorithmic compression

cosmic rain
tawny elkBOT
rich fog
sly shoal
#

not sure if thats the correct way to serialize it

rich fog
#

oh it's an SO itself, so it is serializable by default

sly shoal
#

ah

rich fog
sly shoal
#

that makes sense

rich fog
#

i don't think you can just make new SOs with new and have them get serialized

sly shoal
#

i'd need to actually create an asset for each PassageHandler when i make it?

rich fog
#

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

rich fog
sly shoal
#

nah i dont think i need it to be a full asset. it should only need to exist within the SceneHandler

rich fog
#

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?

late lion
sly shoal
#

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

rich fog
still jungle
# sly shoal hey all. running into an issue with ScriptableObject data being set to null at r...

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

rotund perch
#

Does unity just not have the font to draw these icons? It keeps outputting empty

rotund perch
#

I'm assuming this is gonna spit out some really weird looking characters

#

as it's raw number data converted to raw text data

rich fog
#

they likely aren't printable ascii characters

leaden ice
#

I mean yeah converting random binary data to text is a crapshoot

rotund perch
#

I want to know if it's working though

leaden ice
#

you're better off printing it as hexadecimal or something

rotund perch
#

well raw binary is probably the most efficient way to do it

#

in space at least

rich fog
#

can you look in debugger?

leaden ice
#

hex is much more compact than binary

#

in terms of reading binary data on a screen

#

Hex:
FF

Binary:
11111111

rotund perch
#

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

leaden ice
#

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

rotund perch
#

it's just for saving data, not for displaying anything

rich fog
#

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

leaden ice
#

which displays text

rich fog
#

would be easier to look at the value in debugger or convert to some other format to view it

rotund perch
#

What's the debugger?

rich fog
#

most code editors will have some form of debugger that lets you step through code line by line and inspect the values of variables

heady iris
#

(e.g. JSON)

leaden ice
# rotund perch What's the debugger?

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.

rich fog
#

you can place a breakpoint at the point in code you wish to debug and execution will pause there so you can inspect things

rotund perch
#

or make a hexadecimal converter

heady iris
#

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)

leaden ice
rotund perch
#

oh good

rotund perch
#

I'm just trying to the same amount of data into fewer characters

leaden ice
#

you can feel free to write your raw binary data to a file

#

this would be for reading it in Debug.Log or something

heady iris
rotund perch
#

Yeah I'm using Json so that should help

rich fog
#

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

heady iris
#

Unity can't serialize System.Guid

rich fog
#

just ToString() it

heady iris
#

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.

rich fog
#

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

heady iris
#

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

rich fog
#

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

heady iris
#

I guess you could lazily construct it and then hang on to that object

rich fog
#

guid is a struct so it doesn't really matter how often you construct it, it's all on the stack

heady iris
#

sure, but it's more of a hassle to have to construct it instead of just..accessing a field

rich fog
#

make a property 😄

heady iris
#

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

rich fog
#

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

heady iris
#

hence everyone else saying to just write out hex

rich fog
#

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!

rotund perch
#

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.

rich fog
#

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

rotund perch
#

Yeah json is definitely not very efficient

rich fog
#

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)

sly shoal
#

@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?

heady iris
#

yes, it's not terribly important

rich fog
vague surge
spark vigil
heady iris
#

Terrifying

spark vigil
#

I'm not at my computer but I can write up an example soonish

heady iris
#

I hadn't even considered recreating a union in C#

spark vigil
#

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

#

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

heady iris
#

I'd have used that, but it's editor-only

spark vigil
#

I don't think that one is serializable anyway so there'd be no real point

rotund perch
#

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

spark vigil
# heady iris I hadn't even considered recreating a union in C#
[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

heady iris
#

Is there a reason you haven't just used four ints?

spark vigil
#

Because that would break if the endianness changes

heady iris
#

wouldn't fields A-C break in that case, then?

spark vigil
#

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

cosmic rain
spark vigil
#

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

heady iris
#

Ah, is that just how System.Guid is laid out?

#

I see

spark vigil
#

Yeah

#

Which is why it's allowed to be used in interop

heady iris
#

that's very unique

#

[slowly backing away from Win32]

spark vigil
#

lmao

#

I actually prefer that layout, it makes formatting and a few other things easier

#

also matches the actual guid spec

heady iris
#

right

cosmic rain
rotund perch
cosmic rain
rotund perch
#

yeah I tried with static as well

cosmic rain
rotund perch
#

oh wait

#

I forgot to rename it

#

now it's working, thanks

#

this whole thing could've been avoided if intellisense was intellisensible enough

void basalt
#

I don't think this is something you need to truly worry about

spark vigil
#

Most platforms nowadays are little endian, but imo that's no reason to use the wrong layout

novel bough
#

Hi friends, Is there any way to implement Stripe or PayPal withdraw/deposit into unity?

rigid island
#

I would not recommend you put storing anything in a client / unity game

novel bough
#

okay so there is no direct way to do this on unity right

rigid island
#

not unless they had their own unity sdk which is not likely

#

it would not be secure

leaden ice
#

What platform is this for?

#

Android?

#

Stripe has web, android, etc. sdks

#

you would use those

novel bough
#

Yes, android and ios but with unity

leaden ice
#

Unity runs on android and IOS. YOu would implement stripe as native android and iOS stuff and have that communicate with unity

rigid island
novel bough
#

can i do this with C#

#

okay thanks @rigid island

rigid island
#

uses an account’s secret key, so I suppose its not totally unsafe

valid coyote
#
{
    public NativeList<FixedString32Bytes> MyStrings;
}```

Should this struct work with JOBS and Burst? What would be an alternative?
restive cradle
#

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;
        }
    }```
azure frost
#

Oh god, this player controller script is morbidly broken...

At least, the moving platform motion detection is...

#

Should I post the script?

thin aurora
#

Did you want help or did you just want to vent about an issue you're facing?

azure frost
#

The former. Definitely. I'm terrible with code, and my bro is burned out.

thin aurora
#

If it's the former, then yes. If it's the latter, then please stop posting off topic 😄

azure frost
#

Okay, let me fish it out. I'm working with multiple different computers here.

thin aurora
#

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

azure frost
quick token
#

!code

tawny elkBOT
azure frost
azure frost
#

Anybody still up?

cosmic rain
trim schooner
#

half the world is up

azure frost
#

Well, then my question is, how do I make the platform motion detection work right?

My bro insists that it can be fixed.

cosmic rain
azure frost
#

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...

▶ Play video
leaden ice
azure frost
leaden ice
#

Note I haven't really watched the full video

azure frost
leaden ice
#

Why is that a definite no go

azure frost
leaden ice
#

Why not?

#

🤔

#

Is it an authoring problem?
A performance problem?

#

What's the concern?

azure frost
#

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.

leaden ice
#

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?

#

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

azure frost
#

I think my bro and I should look into this...

#

Sometimes it's all a matter of knowing where to look, I guess.

cyan ivy
arctic sparrow
#

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

cyan ivy
#

That's how I'd approach it too

arctic sparrow
# cyan ivy That's how I'd approach it too

@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

azure frost
cyan ivy
pearl burrow
#

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

vagrant blade
#

Yes, that's much heavier than using wind.

heady iris
#

Skinning will be more expensive.

#

(you'll also have to rig your trees!)

azure frost
azure frost
#

And it's based on Unity's Starter Third Person Character Controller. No rigidbodies there.

cyan ivy
#

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.

azure frost
#

No prob. It got buried.

azure frost
#

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.```
vagrant blade
#

Or buy a feature complete controller on the asset store

azure frost
#

Like that'll ever happen.

west lotus
#

KCC on the asset store is your best bet

#

It’s also free

azure frost
#

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...

cyan ivy
#

The kinematic character controller is a rigidbody based character controller, afaik. And it is pretty neat so definitely do consider it.

azure frost
#

Though I don't quite know if I like this part...

cyan ivy
#

Ah, I'm mixing it up with some other asset ._.

azure frost
west lotus
cyan ivy
azure frost
#

My bro and I have a lot to investigate.

Thanks a million, peeps.

#

I really gotta sleemp now tho

tiny delta
#

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?

quick token
#

also have you tried using an InputActionReference?

tiny delta
#

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

quick token
heady iris
tiny delta
#

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.

wheat cargo
#

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);
wet blaze
#

hello

quick token
heady iris
#

I wouldn't expect anything to appear.

wheat cargo
heady iris
#

You can write a shader that generates new geometry. I presume that's what "point" and "lines" modes are for

wheat cargo
heady iris
#

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

tiny delta
# tiny delta If it helps at all, this is a simplified version of how everything connects righ...

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.

ornate hare
#

does anyone know how to display usernames in photon

rigid island
#

also very doubtful there is anything built in for usernames..

#

that usually comes from auth services, photon is not an auth service

sacred python
#

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?

sacred python
#

ok, so how can i make it possible?

rigid island
#

its pretty diffcult to do I think

#

You have to paint then somehow track those points for another mesh

sacred python
#

like extracting the painted zone a sub mesh of the initial one?

rigid island
sacred python
#

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

heady iris
#

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

lapis otter
#

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...

▶ Play video
#

Thank you!

maiden fractal
# lapis otter So, guys, its not really about coding but about github its my first time using g...

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)

lusty locust
#

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

#

I'm hoping I don't have to completely scrap my current player script.

vagrant blade
#

Do you actually modify the turnSpeed when in the dash state? If it's high, it will be near instant.

heady iris
#

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

vagrant blade
#

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)

lusty locust
#

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.

lapis otter
pine chasm
#

how would i go about spawning a game object directly next to another one, so that their edges are touching but not overlapping?

sacred python
#

has anyone used MIConvexHull in terms of 3D Space?

quick token
#

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

heady iris
#

It's tricky if the objects have complex shapes and arbitrary rotations

pine chasm
#

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

heady iris
#

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

pine chasm
#

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

pine chasm
heady iris
#

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

astral nexus
#

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).

spiral kayak
#

use an enum no?

#

that would be my approach

lusty locust
steady moat
maiden fractal
# lapis otter Thanks for the answer! I see the link, And what will i do with it?I mean, where ...

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

quick token
#

guh, almost enough text to warrant a !.code

fleet bison
#

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

narrow hearth
fleet bison
#

yeah, the constructor line is being printed, but not the Enter() debug line

narrow hearth
#

have you tried attaching vs to unity and walking through what happens?

fleet bison
#

i’m working in jetbrains rider rn unfortunately

narrow hearth
#

hmm i see

fleet bison
#

it seems like the issue is calling functions from the object

somber nacelle
fleet bison
#

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

narrow hearth
#

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

fleet bison
#

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

narrow hearth
#

this isnt the issue but this should be a call to ChangeState

somber nacelle
fleet bison
#

no, haven’t looked into that yet

#

i’m away for a bit so i can check that later though

narrow hearth
#

what does the green squiggle say on (currentstate != null) if you hover over it?

fleet bison
#

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

modern creek
#

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)

hexed pecan
#

So you have CMake 3.22.1?

modern creek
#

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)

hexed pecan
#

I only know that its some sort of build system

steady moat
#

It is, for c++. Usually you have cmake file associated with that.

modern creek
#

hm.. where would i find out how that .. process? is getting kicked off

hexed pecan
modern creek
#

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)

steady moat
#

I would start to look for .cmake file

hexed pecan
#

What's wrong with the instructions shown in the dialog?

#

(Other than not being able to copy it)

modern creek
#

it's referencing adding cmake to a 2022.3 directory

#

(the wrong unity version)

hexed pecan
#

Ah

modern creek
#

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

steady moat
#

Whenever you upgrade you version, you should delete your library

modern creek
#

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)?

odd arrow
#

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

quartz folio
#

Iirc

somber nacelle
#

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

somber nacelle
# odd arrow

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?

quartz folio
#

like what would it return; default?

#

I suppose you just said, it throws

#

that'd be awful 😛

heady iris
#

I know that it defaulted to warning me about non-exhaustive handling of enums

quartz folio
#

yuck! lol

heady iris
#

(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

quartz folio
#

You could consider moving these up; and silencing them via comment where necessary

somber nacelle
#

can confirm that both rider and unity see this as just a warning by default

quartz folio
#

what version are you using?

#

Looks like I do have -warnaserror+ though, so never mind

somber nacelle
#

i'd bet they have the same compiler argument and either forgot they added it, or was added by a team mate

odd arrow
#

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

somber nacelle
#

try restarting the editor 🤷‍♂️
could just be a weird bug

odd arrow
#

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

quartz folio
#

It's 100% on your end, I was wrong because I'm just used to working in projects with -warnaserror+ enabled

modern creek
#

@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

last island
#

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

narrow hearth
#

how would i initialize this dictionary of func's?

last island
#

Do anonymous functions perhaps

leaden ice
#

() means to call the funciton

#

just use Clear alone

narrow hearth
#

ive got a function i want it to link to also Clear alone doesnt work

leaden ice
#

also you would probably need to do this in Awake

#

also your = syntax is incorrect

last island
#

Wouldn't it be () => Clear() ?

leaden ice
leaden ice
narrow hearth
#

im trying to avoid putting it in awake is there a way to do it at compile time?

leaden ice
leaden ice
#

Only if the functions are static

#

you cannot access non static members in a field initializer, no matter what they are.

narrow hearth
#

right i forgot about that

hardy sky
#

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)

leaden ice
#
(overheadCamera.enabled = true```
#

It's == to compare

#

You used = which is assignment

hardy sky
leaden ice
#

You can also get rid of the == true entirely

#

Because it's already a bool

leaden ice
hardy sky
#

i didnt think about that, ill try that

#

thanks @leaden ice

grizzled vortex
#

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 😄

cosmic rain
grizzled vortex
#

hmm good point, let me try those, thanks!

cosmic rain
#

Also, how are you attaching to the build?

grizzled vortex
#

using the debug -> attach unity debugger menu from the visual studio unity extension

cosmic rain
#

I find attaching via the attach to unity button obscures some threads. Try attaching to process instead.

grizzled vortex
#

ah yea that might also help

valid estuary
#

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

somber nacelle
#

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

valid estuary
#

Im not, its literally a new project with zero imports or cusomtiztions

leaden ice
valid estuary
#

Assets\EconSim\EconomyCategoryEditor.cs(8,1): error CS1519: Invalid token '}' in class, record, struct, or interface member declaration

valid estuary
#

which is rediculous because there nothing wrong with my class

leaden ice
#

on line 8

#

Show the fucll script

#

!code

tawny elkBOT
valid estuary
#

yeah, which i pasted above

leaden ice
somber nacelle
#

line 8 is not visible

leaden ice
#

as is everything above it

valid estuary
#
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

somber nacelle
#

so the comment above that doesn't exist?

leaden ice
#

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

valid estuary
#

that IS the full script.

leaden ice
#

that makes no sense

valid estuary
#

My scrrenshot was the same thing just stuff commented out, I removed all that

leaden ice
#

you have a floating attribute without a method it's attached to

leaden ice
#

This is very different from what you shared here

#

(but this one also has 8 lines not showing above it)

valid estuary
#

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

leaden ice
#

You don't need CustomEditor for MenuItem

#

MenuItem only needs a static method, in any class

valid estuary
#

i tried that and it didnt work

leaden ice
#

It works fine for everyone

#

show what you tried

#

and what went wrong

#

(it should of course only be in an editor script since it uses the UnityEditor namespace.)

valid estuary
leaden ice
#

And what's the error here?

valid estuary
#

same thing:

leaden ice
#

Can you show your unity console

#

when you save that code

#

(and tell us which file this is)

leaden ice
valid estuary
leaden ice
valid estuary
#

so apparently that worked but i still have the red line

leaden ice
#

it's just VS acting up

#

Go regenerate project files

#

from the preferences -> external tools menu in unity

valid estuary
#

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

somber nacelle
#

and what is the error when you do that

leaden ice
#

make what work exactly....?

valid estuary
#

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

leaden ice
#

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

valid estuary
#

is it impossible to just add the MenuItem stuff abive this?
[CreateAssetMenu(fileName = "Item", menuName = "Tools/EconomySim/Item")]

#

or does Unity block that

leaden ice
#

what would you expect that to do?

#

a custom editor is not an asset

valid estuary
#

Thats the autogenerated start to a scriptableObject class.

leaden ice
#

you're jumping around

leaden ice
#

which is a custom editor

#

not an SO

valid estuary
#

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

leaden ice
#

why were you shiowing the editor class

#

it was quite unclear what you wanted

valid estuary
#

because thats what all the examples showed

#

All i wanted was a button in a menu at the top to make the SO.

valid estuary
#

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

leaden ice
#

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.

valid estuary
#

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 :)

azure frost
#

(I'm using a PS4 controller on a mac.)

azure frost
#

Ok, it uses InputManager. Mystery solved there.

warm badger
#

is there a way to declare the duration variable as public and use it inside the waitForSecond?

cosmic rain
warm badger
plucky inlet
warm badger
mellow sigil
#
public float waitDuration;
private WaitForSeconds wait;

void Awake()
{
    wait = new WaitForSeconds(waitDuration);
}
plucky inlet
warm badger
#

thanks @cosmic rain @mellow sigil

plucky inlet
night patio
#

has anyone ever made modding support for lua scripting for unity? is there a lua to c# compiler for unity?

night patio
west lotus
azure frost
#

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;
    }
}
cosmic rain
azure frost
cosmic rain
arctic sparrow
#

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

azure frost
wintry crescent
#

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>

main shuttle
arctic sparrow
#

Speed Numbers are fluctuating wildly between a small amount and double digit values

main shuttle
#

Ah, your dividing instead of multiplying in the other code block, nevermind then.

azure frost
lilac jungle
#

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?)

lilac jungle
#

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

tawny elkBOT
lilac jungle
# knotty sun post your !code
using UnityEngine;
using Unity.MLAgents;
using Unity.MLAgents.Actuators;

public class MoveToGoalAgent : Agent
{
    public override void OnActionReceived(ActionBuffers actions)
    {
        //dostuff
    }
}
azure frost
knotty sun
knotty sun
tawny elkBOT
lilac jungle
azure frost
#

Is anybody still here?

azure frost
cyan ivy
azure frost
#

It is

swift falcon
#

Does this server do code review?

maiden fractal
# swift falcon 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.

sleek bough
cyan ivy
maiden fractal
swift falcon
#

Respawning Player

azure frost
#

I think I'm gonna make a thread too.

#

Kinematic Character Controller Woes.

thin aurora
#

Though to be fair, today has been quite a productive day for me

heady iris
#

I resemble that remark

spare dome
steady bobcat
#

Unity plz fix this and respond to my bug report 😦

spare dome
#

looks like you upset unity lol

steady bobcat
#

a few projects are cursed by this, i filed a bug report with some information about hung threads but no response ever

knotty sun
steady bobcat
knotty sun
#

I'll take that as a no then

steady bobcat
#

huh, its not my pc but certain projects but i havent had time to weed out the specific thing

rain minnow
sweet fulcrum
#

[field :SerializeField] public string Name { get; set; }
how to bind this property to label/textfield.value?

leaden ice
#

make an actual custom property that does it

#
public string Name {
  get => myTextField.text;
  set => myTextField.text = value;
}```
#

Not an auto-implemented property

sweet fulcrum
#

want to bind this property to custom editor in ui toolkit

cyan ivy
sweet fulcrum
knotty sun
sweet fulcrum
#

ok

soft escarp
#

is there a function to minimize the unity game window(on build)? i cant find the windows button in KeyCode somehow

placid summit
#

I hate to say "ask a chatbot" but they are unfortunately very useful for this

stable geyser
#

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?

leaden ice
old linden
#

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

noble rover
#

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.

heady iris
#

You can tell the scroller to move to a specific spot, yeah

#

let me go find the script I mashed together for that...

pearl burrow
#

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?

noble rover
#

I'm using UI extensions if that helps!

heady iris
#

oh man this is a little goofy

#

the first class is used to snap a scroll rect to itself when its object becomes selected

#

the second class does the actual movement

noble rover
#

wow amazing! let me take a look, thank you! 🙂

heady iris
#

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

noble rover
#

so would this run on every button? When it either selects or deselects?

heady iris
#

The core idea is that you need to move the content rect so that the item of interest winds up on screen

heady iris
#

or at least a sizable portion of all selectable things!

noble rover
#

in my case they're all buttons for rebinding so it should be simple!

heady iris
#

don't remind me that I still need to do rebinding notlikethis

noble rover
#

are you using the new inputsystem?

fleet bison
#

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

leaden ice
maiden fractal
fleet bison
knotty sun
fleet bison
#

gotcha, thanks

knotty sun
# fleet bison 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

fleet bison
#

oooo yeah i didn't consder that, thanks!

soft shard
# pearl burrow how does GPU instancing works on materials? Lets say i have one single material ...

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

pearl burrow
#

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?

pearl burrow
heady iris
#

I would expect the two meshes to be rendered separately, no matter what's going on with the materials

pearl burrow
#

still one draw for all the meshes (in this case 2)

#

right?

heady iris
#

I would expect there to be two draw calls.

#

Each would render every instance of a single mesh

pearl burrow
#

yes, i hope its this way then!

soft shard
#

In doubt, you should be able to check the Frame Debugger at runtime as well, and see how many instances are created

modern creek
#

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)

gritty jacinth
#

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

leaden ice
#

delete that binding and just bind Left Stick directly

#

as a normal binding

gritty jacinth
soft shard
leaden ice
#

make sure you don't have any processors on the Action

#

(can you show a screenshot of the action configuration?)

leaden ice
gritty jacinth
soft shard
# modern creek no alpha changes

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

modern creek
#

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

soft shard
#

Normally it shouldnt, but you can setup layers that affect your UI or may have changed the layer your UI is on or something

modern creek
#

This is off (which it should be, I think?)

#

hm.. ok, i'll keep digging, thanks

leaden ice
#

Sounds like you want to clamp the magnitude

gritty jacinth
#

I want it to return -1 -1 when I go 45 degrees between forward and left

leaden ice
modern creek
gritty jacinth
leaden ice
#

Why do you think games had weird bugs like walking faster diagonally

gritty jacinth
#

because they were not normalizing the vector after gathering the input

leaden ice
#

Normalizing is wrong

gritty jacinth
#

analog sticks are still supposed to return a value between -1 and 1

#

in all directions

leaden ice
#

Clamping magnitude is correct

leaden ice
#

The thing is at 45 degrees it's not actuated fully left or right

#

It's giving you accurate data

gritty jacinth
#

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

leaden ice
#

You should clamp the magnitude so you get the same with both

#

inputVec = Vector2.ClampMagnitude(inputVec, 1);

heady iris
modern creek
#

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

gritty jacinth
leaden ice
#

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

heady iris
#

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

gritty jacinth
#

ok yhou're right

#

now both devices returning the same value

#

thank you

#

now i gotta remake my blend tree tho 😦

heady iris
#

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

gritty jacinth
#

waitt

#

thats awesome

#

i didn't know youi could put math in the unity fields

gritty jacinth
hexed pecan
#

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

wheat cargo
#

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

mighty juniper
#

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)

gritty jacinth
#

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?

steady bobcat
gritty jacinth
#

and its hard to debug and edit

steady bobcat
#

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)

dusk apex
gritty jacinth
#

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

steady bobcat
#

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

gritty jacinth
#

ima make a small sample with both and see how the code actually winds up

dusk apex
#

How many guns will you have?

gritty jacinth
#

25 or so

steady bobcat
#

SO or not yea up to you. I still encourage the use of good OO programming