#archived-code-general

1 messages · Page 445 of 1

swift falcon
#

wym tho by absolutely necessary

#

like in what case would that be

somber nacelle
#

like if there is some actual technical reason you need a public field over a public property

trim schooner
#

In 15 years of Unity development - I have never come across a need to have a public field

#

Not that there won't be a use , just, you can pretty much easily never use them

steady bobcat
#

how have you never thought "dang i wish i could edit this serialized field outside this component!"

naive swallow
#

Good use case: Adding a temporary debug value you can watch in the inspector in such a way it'll stand out so you know to remove it later

steady bobcat
#

how does it stand out? I use [ShowNativeProperty] from naughty attributes for this purpose.

trim schooner
#
[SerializeField] private SomeType someField;
public float someFloat;
[SerializeField] private SomeType someField2;

Makes it stand out in code. though I'd never do that

steady bobcat
#

Hey i like properties and use em a lot but some things can just be a field

trim schooner
#

If there's some additional code to changing the field (eg: checking for null, or clamping, etc), I want that done in one place and not everywhere I change the field. Regardless of whether or not it needs it now, it might change and require it in the future.. keeping away from public fields and using properties/ methods controls that and removes/ lessens the possibility of future tech debt

#

It's also how my first job taught me in their code standards

safe flame
#

actually this is a good topic for me, what is the difference between property and field?

#

or maybe what are they exactly

dusk apex
#

It mainly depends on preferences. Someone can equally say "I like fields a lot but prefer to have all of my public members be properties".

trim schooner
#

field = your class variables
property = getter/setter

steady bobcat
#

its trivial to update a field to a property in c# (if there is no risk of loosing a serialized value)

safe flame
#

ahhh ok i see

steady bobcat
#

a property makes a getter and setter function around a field for you

safe flame
#

the shorthand to do a getter for something like private int level is public int _level => level right?

trim schooner
#

public int Level => _level;

dusk apex
trim schooner
#

Properties should start with a capital

latent latch
#

I like being verbose and showing the setter ;p

safe flame
#

i see i see, alrighty thanks

steady bobcat
#

public int MyCoolInt {get; private set;}

safe flame
#

(also most of my code right now uses the same level notation for public and private fields lol..)

vestal arch
#

-# camelCase?

safe flame
#

yep

lean sail
steady bobcat
#

Usually it would be PascalCase for public things and camelCase for private/protected. Or you can do m_ if you are stuck in the 80s like unity 🤮

safe flame
#

wasn't it _camelCase for privates?

trim schooner
dusk apex
steady bobcat
vestal arch
#

@safe flame the single most important thing in regards to styling is to stay consistent

chilly surge
#

The more practical reasons to prefer properties over fields are that:

  • Properties can have different visibilities for getter and setter.
  • Property getter and setter can have logic.
  • Interfaces can have properties but not fields. If you ever need to make an interface to encapsulate something, you would never need to refactor anything if you default to properties.
latent latch
#

do people really unscore their private variables outside of python languages

safe flame
steady bobcat
#

js is cus there is no access restructions

vestal arch
#

i mean there is now but it's really new

#

and barely anyone uses it lol

steady bobcat
#

__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED

vestal arch
#

ah no that's just facebook

trim schooner
lean sail
latent latch
#

I've noticed ides nowadays will actually try to hide those variables even if there isn't normally access prevention

dusk apex
vestal arch
#

you guys know the thing about 2 people arguing and then a third person coming in with a really different one that unites the first two people against the third

uhhh so what do y'all think about this

member style/groups are as follows:

  • static fields
  • serialized fields & props (public)
  • own components (no access modifier, assigned on awake)
  • convenience values (no access modifier, computed on awake/start, don't change)
  • containers (no access modifier, initialized immediately, can be mutated)
  • state variables (private, often modified)
  • convenience properties (no access modifier)
  • exposed properties (public)
  • inner types
  • unity messages (no access modifier)
  • inputsystem messages (protected)
  • intercomponent messages/methods (public)
  • coroutines (private)
    member naming: fields and props are camelCase, methods are PascalCase, no prefixes are used for fields/props
#

i mean.. i stay internally consistent lol

steady bobcat
trim schooner
latent latch
#

anyway, snakecase is objectively the base (BEST, but also based) naming convention for variables because you can be verbose as much as possible and not feel bad

steady bobcat
#

rust user alert

trim schooner
#

Wish I was way more consistent though.. got some code I'm re-using and for some reason I used _varName but everywhere else just varName ¯_(ツ)_/¯

safe flame
#

hungarian notation

leaden ice
#

why, like, introduce punctuation in your words though

vestal arch
#

because-why-not?

naive swallow
#

Anarchy mode. Roll a d20 before writing any variable and consult a chart to see which standard to apply to this one

safe flame
#

i have a dartboard for that

steady bobcat
#

private bool __m_b_myBool; 🤡 🔫

vestal arch
safe flame
#

private bool bool_-m_MyBool.bool

lean sail
safe flame
#

pain

steady bobcat
naive swallow
#

Bee Movie notation.

public bool accordingtoallknownlawsofaviation;
public int thereisnowayabeeshouldbeabletofly;
steady bobcat
swift falcon
#

How should I save each object and their position? I'm using a save/load system with a json file and I want to save every object in the scene + their position

lean sail
swift falcon
naive swallow
#

Store them too

swift falcon
#

Its gonna be hard but I will try

steady bobcat
naive swallow
#

Math question: I need to interpolate a height of a 2D spot between its four corners.

Like, I have the height at four points, call em 0,0, 0, 1, 1, 0, and 1, 1. I have a height at each of these four coordinates. Now, if I wanted the height at, say, 0.35, 0.7, how would I lerp that value on both axes? Basically, how can I find the height of an arbitrary point on a theoretical quad given the positions of its vertices?

#

My first thought is "Average the heights of the X lerp and Y lerp:

(Lerp(height[0,0], height[0,1], x) * Lerp(height[0,0], height[1,0])) / 2

But that feels... incorrect. Am I overthinking it?

#

I'm pretty sure that only works if X and Y are equal

#

Wait, no, it doesn't work for any distance, I'm picturing a quad in my head, a quad that's angled down from it's highest point at 0,0, looking for the height at 0.5, 0.5, those two lerps will both be higher than the point I want to actually check

#

So an average wouldn't do

#

Graphic because it's also helping me think this through. There's not actually a quad or I could just do some raycast shenanigans or something, I'm working off of pure math here

sleek bough
#

I think quad is tricky because it can be folded two different ways, (midpart) it's not truly averaged if two opposite vertices higher or lower. Probably point on the triangle should be calculated.

naive swallow
#

If it were a mesh made of triangles it'd be one thing, but what I'm actually dealing with is a 2D array of floats representing the heights of a surface in a grid pattern. I'm trying to get the height of an arbitrary point that is between those array indices

late lion
#

My first thought is this is just bilinear interpolation

sleek bough
naive swallow
#

[Checking wikipedia]
Okay, that does seem like what I need.

Please tell me there's a Mathf function or something I can use for this blobsweat

late lion
#

Looks more complicated than it is when you write it all down like that. Bilinear interpolation is just three Mathf.Lerps. First, lerp between the top corners of the quad by the X. Then the bottom corners by the X. Then lerp between those two values using the Y.

#

For a grid of multiple quads, you find the 4 corners the point is within and calculate the normalized position within that quad and do the same.

naive swallow
naive swallow
late lion
#

I had to double check, I don't often do bilinear interpolation manually. I just remembered having the same aha! moment. Bilinear interpolation is a combination of linear interpolations and trilinear interpolation is a combination of bilinear.

wicked seal
#

Hi, I'm trying to make a Joystick manually and I want to get a sprite to be rendered and updated real time as you move the stick so it looks like the base of a joystick Idk how to explain. I've tried creating a mesh but I just don't get how to update it in real time so it reshapes itself as I move the stick

#

Maybe a rookie doubt but I'm having a hard time with this thing. Does anyone have a good approach to constantly reshape polygons as the game runs?

latent latch
#

What do you mean by reshape? If you're working with sprites then you'd probably want different frames for each direction

wicked seal
#

Like a mobile game joystick

latent latch
#

Well, your choice of 16 different sprite frames, or one mesh where you tilt towards the direction

#

bonus: make the mesh in blender then prebake it into 16 different sprite frames

wicked seal
#

notlikethis is there a way to recalculate the mesh shape each frame? I was thinking on that more than switching between sprites depending on the position of the stick

night harness
#

A mesh/sprite that just looks right when rotated around the centre sounds ideal

wicked seal
#

just making like a cone sticking to a circle would do the trick

latent latch
#

you dont need to reshape anything. Just rotate/tilt the mesh

wicked seal
#

atwhatcost thanks guys

#

I was so immersed on the other Idea I couldn't think about that

fiery steeple
somber nacelle
#

!code

tawny elkBOT
autumn flicker
#

Can Someone Help me fix a bug in my game?

thin aurora
tawny elkBOT
autumn flicker
# thin aurora If you want fixing your bug I suggest you explain in detail what the issue is an...

nullreferenceexception object reference not set to an instance of an object

so i was making a tower Defense game and everything works fine, but after i press the retry button that loads the same scene my enemy object stops moving and going to the waypoint location. the error is in my enemy movement code that takes an array of waypoints(positions) and then orders the enemy object to start moving towards it. but i don't know why the array is null after i reload the scene and i don't know how to fix it.

im new to unity.

ocean hollow
#

is there a prettier way of doing this?

    private void Start()
    {
        if (transform.childCount > 0)
        {
            Transform child = transform.GetChild(0);

            string parentName = gameObject.name;
            Match match = Regex.Match(parentName, @"\((\d+)\)");
            if (match.Success)
            {
                string number = match.Groups[1].Value;
                string newName = $"Arrow ({number})";

                if (child.name != newName)
                {
                    child.name = newName;
                }
            }
        }
    }```
thin aurora
#

Performance wise, put the Regex in a class-scoped variable and make sure to make it a compiled regex. There is an option for that if you make the regex

night harness
thin aurora
#

See the bot message for sharing code

#

The stacktrace should show the file paths of your code and what method/operation it did on what line. This is a very important detail

ocean hollow
night harness
#

i see

#

hopefully not find by name as in Find?

ocean hollow
#

i actually am doing that! in update too! on a lot of different objects!

#

jk lol

night harness
#

the snip is at runtime but if this is just like a editor tooling thing its super easy to have something like this in a menuitem where performance doesnt matter as much

ocean hollow
#

yeah i thought that i might as well add an execute always attribute to make my life easier

thin aurora
# autumn flicker

Thank you. From the stacktrace you see it fails at EnemyMovement line 16

#

So this bit

autumn flicker
#

yeah

vestal arch
tawny elkBOT
thin aurora
#

Now generally Update is called AFTER Start is called, but there are some exceptions

#

To begin, could you change your Start method to Awake?

#

One possible issue is Target might not be set when you use it

#

The second issue could be that Waypoints.points[0] results in a nullvalue

vestal arch
#

do you have a the Waypoint thing set up

thin aurora
#

transform is always set so this will not be null

#

Once this is done, and the exceptions till appears, the next thing to do would be debugging the incoming data

autumn flicker
vestal arch
#

are they in different scenes or something? what's your setup here exactly?

autumn flicker
thin aurora
vestal arch
#

thonk wait it should delete and reawaken Waypoints too

#

unless it's DDOL...?

vestal arch
#

scroll all the way up

#

is it the same one, or does it perhaps point to somewhere else instead?

thin aurora
vestal arch
night harness
vestal arch
#

which meant target wasn't getting set, since it errored before that

#

check your set up, do you actually have children in the object that has Waypoints?

thin aurora
vestal arch
#

is anything DDOL?

#

do you have multiple Waypoints in the scene?

night harness
thin aurora
#

I suggest you do the logging I told you about

thin aurora
#

In this case I'd also log the child count specifically in your waypoints method

#

See if it has any. I assume it either doesn't log, or it logs zero

thin aurora
vestal arch
autumn flicker
thin aurora
autumn flicker
thin aurora
#

Do these waypoints even exist on a reload?

autumn flicker
thin aurora
#

So it doesn't log on the reload meaning it keeps the old objects int he static array

#

One thing you can do is get rid of the static context and make it a singleton, but ideally it just gets called again

#

What happends if you change the log to Debug.Log("message", this); and press it when it shows. Where is your waypoints object?

#

The object should have its Awake method called when it initializes, which is what it would do on a reload. In your case this does not appear to happen judging by the single log message

autumn flicker
thin aurora
thin aurora
#

So it does run?

autumn flicker
#

the second one is after the reload

vestal arch
#

@autumn flicker how exactly are you achieving the reload?

#

just SceneManager.Loading the same scene?

thin aurora
#

It does not point to anything from your previous screenshot

#

I assume it's the first index of your waypoints still?

autumn flicker
thin aurora
#

Your second Debug.Log still points to the same location with the waypoints when you click it?

#

It seems like in the case of a reload it does not fill the array anymore because it has no children

#

And in turn Target remains null

#

But now the question is why it would no longer have them on a reload, suggesting the way points might be loaded at a later stage?

#

How are those waypoints added?

autumn flicker
thin aurora
#

No I mean the actual game object instances in the hierarchy

thin aurora
#

Are these added by code?

autumn flicker
#

its in the scene

thin aurora
#

You could also just suffer from some sort of race condition in that case

#

These are prefabs though. You have these added through the designer?

#

Then we can rule it out at least

autumn flicker
#

the pink dots are the waypoints

night harness
thin aurora
#

The waypoints have no behaviour as far as I know

#

The parent game object collects them, then it will tell the enemy where to go

#

So far this all makes sense, I just don't see why it would break on a reload

steady bobcat
#

Perhaps its time to use a debugger

vestal arch
narrow summit
autumn flicker
vestal arch
#

the DontDestroyOnLoad part

#

you've marked some stuff as DontDestroyOnLoad, so just to make sure, you haven't put anything that relies on waypoints in there?

autumn flicker
thin aurora
#

I'd take Rob's advice and look into learning how to use the debugger

thin aurora
#

See the topic for Debugger

steady bobcat
#

Its often the best way to actually figure out an issue

#

that and useful logs

thin aurora
#

I think there's not much else to do here because it's likely there might be an issue that fixes itself before you even notice, but the code is invalid at that point

night harness
#

what scenario can actually trigger an outside index error on an array at index 0?

#

i thought it would be throwing a null ref on the array

#

wasnt aware an array could exist with no indicies?

thin aurora
#

The array has a size of 0, so index 0 is out of bounds

night harness
#

ah

thin aurora
#

And in turn, Target remains null and will always throw a null ref

#

So we initially started there, but the issue is the empty array

#

But hey, we learn debugging which is always good

night harness
#

well more specifically accessing at 0 throwing the error was what i was curious about but yeah

autumn flicker
#

yeah i know but i don't know how to use a debugger because im new to this stuff so i preferred to ask people to help me out. Anyway, thank you guys.

autumn flicker
vestal arch
#

see if they're consistent once you reload the scene

steady bobcat
#

VS code has a debugger you can use with unity as long as you have the unity vs code extension + set vs code as the editor in unity.

autumn flicker
vestal arch
autumn flicker
vestal arch
#

do you have multiple Waypoints components?

autumn flicker
#

24 waypoints

#

and the awake method logs them all

#

but the start method only logs one

vestal arch
#

..you have Waypoints on each of your waypoints, don't you

#

Waypoints should only be on the container for the waypoints

#

otherwise you're just overwriting the static array when it loads for the children

vestal arch
#

thta doesn't answer my question

#

im not psychic lol

autumn flicker
#

each one has the waypoints script

autumn flicker
#

you were right

#

only the parent object that hold the waypoint should have the script

#

not every one of them

#

thank you alot

vestal arch
#

!collab

tawny elkBOT
#

:loudspeaker: Collaborating and Job Posting

We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
Collaboration & Jobs

thin aurora
#

How did this even work in the first place then

#

Also, how did they not all log a message if they have the script? You only had a single log and they didn't collapse

#

So many questions

#

Also because when I said to add this to the parameter and click it, it would've gone to the parent game object

#

Anyway, glad it's fixed

autumn flicker
autumn flicker
thin aurora
autumn flicker
#

Thats the thing that confused me

sturdy holly
#

not sure the best place to put this but we are using I2 for localization and it works fine EXCEPT we have some key values such as 75% and on import it seems to be converting this to a value 0.75 etc can we stop this?

chilly slate
#

Hey is it possible to utilize system level actions in unity?

vestal arch
chilly slate
# vestal arch could you elaborate on what you're referring to

Basically making a project for school stuff atm, I need to essentially implement stuff like how inscryption is able to read through your hard drives. Or just ways generally to interact with the system like being able to create textfiles on your desktop or shutting down a PC through the game

vestal arch
#

oh, syscalls?

#

but uhh shutting down the entire pc i think could constitute as malware so maybe don't lol

sturdy holly
#

yeah you generally dont want to mess with peoples systems like that, can you do it? yes

vestal arch
#

a little googling seems to indicate that you can use normal c# fs apis (System.IO) except on browser where there isn't an fs

chilly slate
#

Not a project meant to be distributed through like steam or something like that though im still gonna look at the terms n agreement for unity tho

#

Thanks anyhow

sturdy holly
# chilly slate Thanks anyhow

yeah no worries but you can do it fine, you can access anything you need via win32 api and even some in build unity functionality

vestal arch
soft shard
#

Although if you do decide to go through win APIs, a cool one ive discovered is that you can set the name of the application when its in windowed mode, helpful in multiplayer

fiery steeple
fiery steeple
thin willow
#

I am having a bit of confusion about mathf.smoothdamp, and why it is at all framerate dependant in my setup in-game (VRChat world, which uses unity).

  • I have a test script to simply move a cube from y=0 to 1. Run in Update(). Using unity default (time.deltaTime).
  • the parameters are all typical initially:
    current value=0
    target value=1
    currentVelocity=0
    smoothTime=0.1
    maxSpeed=default (mathf.infinity)
    deltaTime= default (time.deltatime)
  • My understanding is, mathametically, the overall duration to reach say 0.95 should be similar or equivalent for different framerates. Becuase the actual movement curve is the same, just the steps are different in different framerate.
  • I asked GPT (I know, dont trust AI etc) to make a calculator to check the overall time to reach 0.95. It generated a code that runs the unity smoothdamp and measures the time it takes. I ran the code seperately and it seems to confirm, the times are about the same.
Time to reach 95% of the target at 15 FPS: 0.2667 seconds
Time to reach 95% of the target at 30 FPS: 0.2667 seconds
Time to reach 95% of the target at 60 FPS: 0.2500 seconds
Time to reach 95% of the target at 120 FPS: 0.2417 seconds
  • However my in-game measurements (using similar method, by comparing the starting time, and the time it reached say 95%) are like this:
15 FPS, ~466 ms
30 FPS, ~666 ms
60 FPS, ~1100 ms
90 FPS, ~1567 ms
120 FPS, ~1.9 seconds

which is a whole lot of difference and cannot be explained simply by step size resolution.
Moreover, in VRChat you can press esc to open a menu which will lower your FPS for maybe a few frames. I can visibly "speed up" the cube movement by pressing esc therefore lowering the FPS for a few frames.

leaden ice
thin willow
#

oh this maybe difficult because it is done in VRChat's udon graph

leaden ice
#

how does udon graph handle ref parameters?

thin willow
#

interestingly, it does not, i have to leave the nodes unplugged to get it to work, i assume this is handled in the background

#

you are talking currentVelocity correct?

leaden ice
#

yep

thin willow
#

would the currentVelocity not being updated create such effect? i mean visually it seems to be damping just fine

leaden ice
#

absolutely yes

#

i mean i don't think it would be working at all though if it wasn't handling the velocity properly

dire pelican
#

How would I go about getting rid of seams between different meshes?
I think Im supposed to recalculate the normals by hand so they take in account the vertices of neighboring meshes but im not sure how to do this with a noisy sphere

hexed pecan
#

!code

tawny elkBOT
dire pelican
hexed pecan
#

So does the sphere consist of 6 parts?

dire pelican
#

I just calculated normals by normalizing the difference between the vertex and the center of the sphere

dire pelican
#

so it depends

hexed pecan
#

How did it look when you tried RecalculateNormals?

#

Are you even sure that it's a normals issue and not a vertex color issue?

#

Oh you aren't using vertex colors

#

In that case maybe a UV issue

dire pelican
#

the shadows are just lacking

hexed pecan
#

What renderpipeline are you using

dire pelican
#

URP

hexed pecan
#

Have you looked at the mesh with rendering debugger on

dire pelican
#

Let me see

#

this is the lighting with "lighting with normal maps"

#

there's a visible seam, altho im not sure if thats what im supposed to do

dire pelican
hexed pecan
#

I'd recommend to rework it so that the vertices are shared. Then RecalculateNormals should produce smooth normals at the seams

dire pelican
hexed pecan
#

The normals are calculated per-vertex from the neighbors of the vertex. If your mesh has disconnected parts (like at the seams here), these seams will appear

hexed pecan
# dire pelican How would that work?

You can try using something like a Dictionary<Vector3, int> to check for duplicates. The vector is the vertex position, the int is the index of the vertex at that position

dire pelican
#

It seems like the meshes are sharing vertices but lemme check

dire pelican
#

Hm I don't think there are duplicates.

#

Let me try to see if I can fix that.

hexed pecan
#

You don't want duplicates. You want shared vertices at the seams

vagrant blade
#

There are no memes here, thanks.

fiery steeple
sturdy holly
#

I just found out about the "GameplayMessageSystem" but I cannot see it in the plugins list, was this nuked/renamed etc?

rigid island
#

nothing shows up relevant to unity..

#

you lost from /unreal ?

sturdy holly
#

haha yeah wrong channel 😄

signal moon
#

Hi! How do I restart the game? Like completely in the exact state as if I launched build again or clicked play in editor. I tried simple scene one, but I saw massive amount of unassigned things out of nowhere and non reseted variables. Any workaround?

#

Ofc finding every single variable and setting it to what it should be is out of the question lol

steady bobcat
vestal arch
rocky heron
#

oh okay my bad 😢

vestal arch
#

though it seems like you just might be getting different amounts of random values

#

also UnityEngine.Random is shared across everything, so maybe consider System.Random for a localized deterministic thing

rocky heron
#

welp i wont pry any further, my bad didnt know about the modding thing

vestal arch
# rocky heron welp i wont pry any further, my bad didnt know about the modding thing

the reason modding discussion isn't allowed here is partly for legal reasons and partly because modding covers some topics that aren't relevant to general unity development

but i skimmed your question and it doesn't seem particularly bound to modding, so maybe try booting up an empty "test" project (to eliminate the modding aspect, in the sense that it doesn't have an effect on the behaviour), and if you can replicate the behaviour there, you could ask about that

#

thonk im not sure if that would count as rule evasion, so.. if a mod smites the convo don't be surprised i guess lol

rocky heron
#

just gonna make a cool shuffle function rq ^-^

signal moon
steady bobcat
signal moon
rocky heron
# vestal arch the reason modding discussion isn't allowed here is partly for legal reasons and...

just made it in a test and it works fine in there 😔

 void Start()
 {
     Random.InitState(2);
     List<int> list1 = new List<int>() { 1, 3, 12 };
     List<int> list2 = new List<int>() { 1, 3, 12, 10, 100, 5 };
     Shuffle<int>(list1);
     Shuffle<int>(list2);
     print("list 1:");
     foreach (int i in list1)
     {
         print(i);
     }
     print("list 2:");
     foreach (int i in list2)
     {
         print(i);
     }
 }

 void Shuffle<T>(List<T> list)
 {
     for (int i = 0; i < list.Count; i++)
     {
         Swap<T>(list, i, Random.Range(0, list.Count));
     }
 }
 void Swap<T>( IList<T> list, int i, int j)
 {
     T val = list[j];
     T val2 = list[i];
     T val3 = (list[i] = val);
     val3 = (list[j] = val2);
 }
#

this i think is about the same and it just works

#

now im super confused

vestal arch
#

what's with the val3 lol

steady bobcat
rocky heron
vestal arch
#

that's built-in?

rocky heron
vestal arch
#

wdym "the game"?

#

oh repo?

rocky heron
#

yes

vestal arch
#

why would they do it like that...

#

oh

#

it's from decompilation

rocky heron
#

yeah

#

ofc

#

prob not perfect

vestal arch
#

definitely not perfect

signal moon
steady bobcat
#

Tbh i dont know what unity will do if you single load into the same scene as you have loaded already

vestal arch
#

(fyi, swap only needs 1 extra variable

void Swap<T>(IList<T> list, int i, int j) {
  T temp = list[i];
  list[i] = list[j];
  list[j] = temp;
}
```)
signal moon
#

I had a lot of nulls and other problems, suddenly 50 critical warnings

vestal arch
vestal arch
#

that only works when you have access to the underlying bits; this is the general case

signal moon
#

When I looked in inspector half of the things were unassigned

rocky heron
#

but i dont see how itd make a difference

#

since im not looking at the list from dictionary

#

but a different one

vestal arch
# steady bobcat xor swap would like a word

xor swap still needs an extra variable

void Swap<T>(IList<T> list, int i, int j) {
  list[i] ^= list[j];
  sanity--;
  list[j] ^= list[i];
  sanity--;
  list[i] ^= list[j];
  sanity--;
}
steady bobcat
#

Huh isnt there one where you can use 0 extra vars?

vestal arch
steady bobcat
#

probably doesnt work in c# though

vestal arch
vestal arch
chilly surge
#

You can just do the tuple swap (a, b) = (b, a);.

steady bobcat
#

Ha im slow
yea in c/cpp or using unsafe in other langs

rocky heron
vestal arch
#

-# so apparently "cs type" gives results about caesarian section types

vestal arch
vestal arch
#

yeah but what you just showed doesn't seem very close to the structure you had originally

#

make dummy dicts and stuff

rocky heron
#

ill redo every class in there then ig

vestal arch
#

you don't have to replicate the entire project structure

#

just the parts relevant to this

#

at least keep the original flows you tested

rocky heron
#

i found it out but thanks for the help :) for some reason the count of the first list was going up by 3 after each reload of my save, which it shouldnt. every time i reset the game and loaded it the count stayed the same

dawn nebula
#

Let's say I have a collection of Sprites that represent the elements in Unity. I want his collection to be used across many GameObjects. How should I set this up?

#

ScriptableObjects?

night harness
#

sounds about right

dawn nebula
night harness
#

I tend to, depends on what kinda workflow you end up prefering

eager yacht
#

In a work project we basically just have this (an SO) and some functions on it to grab what we want from ids and such. It's nice and simple tbh.

dawn nebula
#

what are the Ids? Ints or strings?

eager yacht
#

Contains whatever we want to access in various places. Prefabs, sprites, settings, etc. And we just have a static class with some constant ids for things like items, otherwise we can always just search with a string (such as a prefab name).

hard mantle
#

Why Unity's IPointerDownHandler interface event giving a 6 digit and different pointer id in eventdata.pointerID. it used to give touch Id like 0, 1 before Unity 6. It broke my game!

cosmic rain
hard mantle
#

I really hope it is bug

cosmic rain
hard mantle
#

I just debug on event callback eventData.pointerID.

Whenever I click on the UI where the script is placed. It gives me different pointer id every time like
3562651
3562652

#

It used to give 0 when only 1 finger is there

#

And when 2 it give 1

#

And so on

cosmic rain
#

It also seems that the implementation is dependent on the input system

hard mantle
#

There's no connection with this interface and input system

#

It works on my unity 2022 project

#

The same script produces different pointer id in unity 6

cosmic rain
hard mantle
#

Ohh

#

I am using new input system in unity 6 project

cosmic rain
#

And in unity 6 I think the input system is set to be active by default

hard mantle
#

Yes

cosmic rain
hard mantle
#

Why it's needed to me.

I made a touch area for mobile users where they can move cinemachine camera

#

The touch area is a ui

#

And I need finger ids to make sure the touch on UI will move the camera and not the touch outside ui

cosmic rain
hard mantle
#

Thanks a lot for your time @cosmic rain

sturdy thorn
#

Excuse me I need help
I have a scene and there is an input field, a code must be written in order to play the game.

#

The thing is that the code is generated in a html website

#

how do I connect Unity to my website?

cosmic rain
sturdy thorn
#

Sorry

chrome sage
#

is there a resource for best practices for pixel perfect 2d collisions? preferably with rule tiles? I'm apparently doing something weird.

vestal arch
#

you didn't want collisions tho did you?

#

you just wanted a traversable grid, right?

chrome sage
#

with walls, yes

deep echo
#

yo, for some reason when i bake, its not showing me what i baked? any ideas? i am using navmesh surface

#

and also i am tryna make a cube follow it, for some reason it isnt,'

young tapir
deep echo
#

mb

young tapir
chrome sage
#

since i didn't get an answer ill ask again, is there a resource for best practices on detecting overlap for collisions?

vestal geode
steep herald
#

Sanity check please. Anchor's parent is container, so essentially giving the view object the same parent, then assigning the same position and rotation.

Works fine the first time this is displayed, second time the view prints (0, 0) and the anchor prints (the real non zero X, 0)

Something does mess with the parent's scale but it should still work fine afaik

var view = ObjectPool.Instance.Take<BasicSpellView>();
view.RectTransform.SetParent(container);
view.transform.localScale = Vector3.one;
view.transform.SetPositionAndRotation(anchor.position, anchor.rotation);
print(view.RectTransform.anchoredPosition);
print(anchor.GetComponent<RectTransform>().anchoredPosition);
olive ridge
#

guys how do i make a mesh that looks something like this?

#

the big dot is a city, the small dots are vertices, the blue part is the mesh/triangles

#

most tutorials just tell you how to make a square with it

steep herald
#

@olive ridge same as you'd make any mesh but there's a default import setting that trims loose verts, you have to turn it off if you want to keep them

hexed pecan
olive ridge
hexed pecan
#

You can make meshes in a 3D modeling program. People come here with non-code questions all the time so that's why I'm asking

olive ridge
hexed pecan
#

What would the mesh be used for?

olive ridge
#

as i want it to be a map game so the territory around cities would be dynamic

olive ridge
hexed pecan
#

Delaunay triangulation might be useful if you want to turn a bunch of points into a triangulated mesh

#

And/or voronoi diagrams

olive ridge
#

that thing you can get on github?

hexed pecan
#

Those are just algorithms, but yeah there are implementations on github

olive ridge
#

oh

hexed pecan
olive ridge
#

are there tutorials?

steep herald
#

Yes

olive ridge
#

could u send?

hexed pecan
#

I feel like that advice was more for premade meshes, not generated ones?

olive ridge
#

oh

hexed pecan
#

(Which prompted me to clarify that you are generating it)

bitter hill
#

I want to get the number of frames or just the time left in an animation clip with the animator, is this possible?

chrome sage
gray thorn
#

    public int FrameNumber;
    public uint SeedState;
    public ReplayFrameFighter[] Fighters;

    public ReplayFrame(int _frameNumber, uint _seedState, int _fighter_count, BaseFighter[] _fighters) {
        FrameNumber = _frameNumber;
        SeedState = _seedState;

        Fighters = new ReplayFrameFighter[_fighter_count];
        var n = 0;
        for  (var i=0;i<_fighters.Length;i++) {
            if (_fighters[i] == null) continue;
            Fighters[n] = new ReplayFrameFighter(i, _fighters[i].input.inputs[0]);
            n++;
            if (n >= _fighter_count) break;
        }
    }

}```
hey im getting a gc.alloc in the `ReplayFrame` constructor. obviously to do with the array, but is there not anyway to just have a fixed array in a struct without generating garbage?
#

ReplayFrameFighter is a struct if that matters

vestal arch
leaden ice
#

also clearly it's not a fixed array because you're initializing it based on _fighter_count

#

new ReplayFrameFighter will also create garbage here if ReplayFrameFighter is a class

steady bobcat
chrome sage
steady bobcat
#

poo poo c#

glossy ledge
thick terrace
vestal arch
#

also, do you really need this? could you perhaps add a properties to BaseFighter that give it similar capabilities to ReplayFrameFighter?

#

that way you could just use the same array in a different way, rather than making a new one

rugged storm
#

yo I'm figuring out non mouse UI navigation, how when a new peice of UI to move the selection to that

#

like for existing Ui at the start of a scene I can use the first selected think in the event system but i dont know how to make that work with seperate UIs, like say the options menu or pause menu

leaden ice
swift falcon
#

using UnityEngine;

[RequireComponent(typeof(Rigidbody))]
public class PlayerMovement : MonoBehaviour
{
public float moveSpeed;
public float rotationSpeed;

private Rigidbody rb;
private float moveInput;
private float rotationInput;

void Start()
{
    rb = GetComponent<Rigidbody>();
}

void Update()
{
    // Inverted vertical input so W = forward
    moveInput = -Input.GetAxis("Vertical");

    // Left/right rotation input (A/D or Left/Right)
    rotationInput = Input.GetAxis("Horizontal");
}

void FixedUpdate()
{
    // Move forward/backward
    Vector3 move = transform.forward * moveInput * moveSpeed * Time.fixedDeltaTime;
    rb.MovePosition(rb.position + move);

    // Rotate left/right
    float rotation = rotationInput * rotationSpeed * Time.fixedDeltaTime;
    Quaternion turn = Quaternion.Euler(0f, rotation, 0f);
    rb.MoveRotation(rb.rotation * turn);
}

}

i hace a problem. When using the S and D forward, it acts ok, but when i face the error which the right is left and righht is lwft. How can i fix it? (it is for a tank)

tawny elkBOT
swift falcon
#

i never used that

swift falcon
#

it ccreates

#

a code like box

#

i don't get it

#

fr

rigid island
swift falcon
rigid island
#

yes

swift falcon
#

it is the sript of making a tank respond to w a s d commands

#

it partially does

#

but backwards takes a as d and d as a

rigid island
swift falcon
#

what could be the source of problem

rigid island
rigid island
swift falcon
#

entire

rigid island
swift falcon
swift falcon
ivory wagon
#

anyone know how to fix this it happens when i enter playmode and move my mouse i have a code that makes the camera and character follow the mouse but its not working -_- im trying to get my guy to turn left in right in a first person view but the camera and person is messing up

chrome sage
#

k is there an up to date top down dungeon tutorial for unity 6? i feel like i should go shoot myself since i cant seem to figure out this basic fucking problem

rugged storm
leaden ice
#

Or in OnEnable in a script on the menu

rugged storm
chrome sage
#

so do you people not use rule tiles because they break collisions? or is there other reasons why you should never use rule tiles?

leaden ice
ivory wagon
#

ok

#

ill send it

leaden ice
#

also multiplying Time.deltaTime into mouse input - another no-no

ivory wagon
#

ok

#

thanks

leaden ice
#

And if you plan to move this into FixedUpdate - reading mouse input there would also be bad

#

you need to read and accumulate the mouse input in Update, then apply/consume it in FixedUpdate

ivory wagon
#

ok thank you i will fix it

leaden ice
#

It's also not totally clear what this is actually for - first person controller?

ivory wagon
#

yeah fps shooter

leaden ice
#

then don't use moveRotation

#

just do rb.rotation *= Quaternion.Euler(0, mouseX, 0);

#

and get rid of Time.deltaTime

#

and you'll be good

#

(no FixedUpdate)

ivory wagon
#

ok will do this was really helpful thank you.

#

wait so would something like this work?

using UnityEngine;

public class MouseLook : MonoBehaviour
{
public float sensitivity = 2f;
public Transform cameraHolder;
public Rigidbody playerRigidbody;

float xRotation = 0f;

void Start()
{
    Cursor.lockState = CursorLockMode.Locked;
}

void Update()
{
    float mouseX = Input.GetAxis("Mouse X") * sensitivity;
    float mouseY = Input.GetAxis("Mouse Y") * sensitivity;

    // Vertical camera movement
    xRotation -= mouseY;
    xRotation = Mathf.Clamp(xRotation, -90f, 90f);
    cameraHolder.localRotation = Quaternion.Euler(xRotation, 0f, 0f);

    // Horizontal  body rotation
    playerRigidbody.rotation *= Quaternion.Euler(0f, mouseX, 0f);
}

}

fathom cove
#

!code

tawny elkBOT
ivory wagon
#

what?

rigid island
ivory wagon
#

ok

rigid island
#

format the code correctly for others

neon pivot
#

Hey, I'm trying to animate a position from point A to point B using an AnimationCurve, how would that be possible?

surreal forge
#

yo, question, i use playmaker, how i can made a bubble for make some asset invisible when my character go on back of them ? thx ! 🙂

#

or when we don't see the player

leaden ice
#

e.g.

public AnimationCurve myCurve;
public Transform start;
public Transform end;
public float duration = 1f;
float timer;

void Update() {
  timer += Time.deltaTime;
  timer %= duration; // make it loop, just for demonstration purpsoses
  float t = myCurve.Evaluate(timer / duration);
  Vector3 position = Vector3.Lerp(start.position, end.position, t);
  transform.position = position;
}```
night harness
#

Would obviously need to profile it to get contextual answer but just curious, There’s a notable amount of overhead in the act of instantiating something right? Like if I instantiated a prefab that had 8 other prefabs as children that’s gonna be lighter than if i instantiated the first prefab than instantiate each child prefab?

rigid island
#

I think I read that in reverse, I meant my assumption would be its heavier doing more objects all at once than spanned over time @night harness

#

ofc also depends what's on those children / prefab in term of components

night harness
#

oh interesting, im guessing that might depend on the scale in question though right? I'm talking like pretty small overall (eg. imagine an enemy spawning with 3-4 prefabs under it). where i'd imagine maybe there would be more overhead in sending the instansiation requests 4 times rather than just once but i guess it's fairly hard to guess

rigid island
#

imagine you have 8 Start methods running at once doing work , big hitch

leaden ice
#

"notable" is going to be subjective though

night harness
# leaden ice probably, yes. Nav has a point but it's more about spreading the work out over ...

fair. I guess in the context of what I was asking about doesn't help though (which i didn't provide so my bad on that, early in the morning aha). Doing fairly vague prototyping of how I want to handle code architecture for generic content in various prototypes and weighing up various solutions to problems i'm running into

In this case I'm thinking about how I kind of want the root of any content prefab to be kinda a BehaviourController/EntityManager with the different types of behaviours (eg. hurtable, interactable, valuable, movable etc.) as children of the parent whether that's literal or just logical rather than just having those behaviours be the main prefab script so i can mix inheritence and composition and all that

#

but there's a lot I gotta consider when implementing that kinda thing in how everything talks together, what the prefab setup would look like, what the scriptableobject would look like etc. etc.

#

so just messing around with stuff

rigid island
#

how much work each component does plays a huge part in it as well

night harness
#

yeah forsure. im happy thinking about all this when it comes to items, player, enemies etc. but then my mind panics thinking about how much work i'd be adding to projectiles that die in half a second 😭

#

I know those should really have just a different solution altogether but i enjoy the idea of having everything managed the same way

rigid island
#

anything you're going to reuse don't forget about Pooling , oh and polling can be other things besides gameobjects too

#

really does help recycling what you already allocated rather than cleanup , re allocate cleanup and repeat

night harness
#

if you have a serialized base/poco class stored on a prefab there's nothing in the scope of the class itself that is able to tell when it's been created right? since the constructor is run when the prefab asset was made?

leaden ice
#

the constructor will be called on your serialized POCO just... maybe not when you think it will be

night harness
#

I wanted the equivalent to an awake call in my poco class

leaden ice
#

for what purpose though

#

what do you plan to do there?

night harness
#

I wanted certain logic classes in my monobehaviour that initialized by themselves to certain extents, more-so curious if it's possible than any ironed out vision

#

it's fine if the answer is just no

leaden ice
#

It just... depends on what kind of initialization we're talking about

#

that's why I'm probing

#

if you mean like "I want to do something right after the serialized fields are assigned by the serializer", then the link I posted above is for you.

night harness
#

nah i mean like runtime game logic typa stuff

leaden ice
#

this is for runtime

night harness
#

I just honestly did not consider those run at runtime

#

even though yeah that makes sense huh

next estuary
#

hi! i just wanted a bit of advise, i have some bugs and i wanted some help, do i ask here or on the beginner one? (i know its dumb)

leaden ice
next estuary
#

thx

fair silo
#

Hello, I have a code that works for 3 of 4 of my players, but not my 4th player for some reason. Even with the code being the same it just won't assign anything keepint player4Choice void

#

void BypassSelection()
{
Debug.Log($"BypassSelection: Player 4 choice is {player4Choice}"); // Add this debug log to verify assignment

    player1Choice = "1";
    player1FeedbackText.text = "P1 selected: 1 (Testing Mode)";
    HighlightSelectedButton(player1Buttons, "1");
    DisableButtons(player1Buttons);

    player2Choice = "2";
    player2FeedbackText.text = "P2 selected: 2 (Testing Mode)";
    HighlightSelectedButton(player2Buttons, "2");
    DisableButtons(player2Buttons);

    Debug.LogError("Testing mode: Player 3 choice is set to 5.");
    player3Choice = "5";
    player3FeedbackText.text = "P3 selected: 3 (Testing Mode)";
    //HighlightSelectedButton(player3Buttons, "3");  
    //DisableButtons(player3Buttons);  

    player4Choice = "6";
    player4FeedbackText.text = "P4 selected: 4 (Testing Mode)";
    HighlightSelectedButton(player4Buttons, "4");
    DisableButtons(player4Buttons);
leaden ice
#

those errors can be eliminated when you just use arrays and loops instead of duplicating code N times.

#

anyway this code doesn't make much sense to me, so it's hard to say what's going wrong. It's not clear what this code is supposed to do.

night harness
#

Is serialization synchronous? as in if X object runs OnBeforeSerialize will it's OnAfterSerialize always run before any other objects OnBeforeSerialize will run?

cosmic rain
# night harness Is serialization synchronous? as in if X object runs OnBeforeSerialize will it's...

It could be. It could be not. This is probably something you shouldn't rely on.

Work performed in these callbacks must be done with care, as the Unity serializer runs on a different thread from most of the Unity API. It's recommended to process only fields that are directly owned by the object, to keep the processing burden as low as possible.

https://docs.unity3d.com/6000.1/Documentation/ScriptReference/ISerializationCallbackReceiver.html

#

We can't say for sure if it's just one thread or a pool of threads and there's no guarantee it would stay the same in the future.

night harness
#

Yeah 🤔

#

Was playing with something like this to allow for a prefab to reference itself as an asset rather than it's own instance

public class PrefabBehaviour : MonoBehaviour, ISerializationCallbackReceiver
{
    private static PrefabBehaviour _serializationTemp;

    [field: SerializeField] public PrefabBehaviour Self { get; private set; }


    void ISerializationCallbackReceiver.OnBeforeSerialize()
    {
        _serializationTemp = Self;
    }

    void ISerializationCallbackReceiver.OnAfterDeserialize()
    {
        if (Self != null && _serializationTemp != null)
        {
            Self = _serializationTemp;
            _serializationTemp = null;
        }
    }
}
#

I noticed this in the serialization guide

Unity runs the same serialization code in a different variant to report which other UnityEngine.Objects it references. It checks all referenced UnityEngine.Objects to determine if they’re part of the data Unity instantiates. If the reference points to something external, such as a Texture, Unity keeps that reference as it is. If the reference points to something internal, such as a child GameObject, Unity patches the reference to the corresponding copy.
and realised in theory you could use these callbacks to quickly chuck the reference out of the patchers eyesight and slide it back in after the fact

cosmic rain
#

Why not just hold references to the prefabs in, say, other prefab or an SO?

night harness
#

Def giving osha violation vibes, just testing the waters abit

Potentially has some nice benefits when dealing with networking for specific reasons that im forgetting but i remember I was looking for a way to do this

#

I think it was due to how it could help manage the order of execution of content spawning because without multiplayer i'd tend to just spawn a prefab via reference on a so then give the instance the so so it knows what data to care about, but in networking as a client I can't directly get a reference to the object i requested to spawn because that's an rpc that has to travel to everyone? something like that

#

would be cool to reliably do in general just for the sake of doing it though

cosmic rain
#

There are probably many good ways to go about it without relying on the approach with serialization that you brought up(there are probably other issues with it).

night harness
#

Probably

#

To be honest I think there's an aspect to it where I just don't like that I can't do it 😛

cosmic rain
#

That's something you just have to accept when working with third party close sourced engines.

#

You have to accept the rules of the game.
Or go and write your own engine/modify an open source one.

night harness
#

we'll see i guess 😄

wild nebula
#

In Unity Localization, how do you add a list as argument?
{0:list:{typeName}: {fromValue} -> {toValue}|\n}
Right now I am trying to make item description from these.

Example description:
Damage: 5 -> 7
Agility: 3 -> 5
Defense: 1 -> 2

glossy ledge
# chrome sage k is there an up to date top down dungeon tutorial for unity 6? i feel like i sh...

I see you use transform to move your collider(https://paste.mod.gg/dvgmgkkoeacz/0) , you should probably use moveposition (https://docs.unity3d.com/6000.1/Documentation/ScriptReference/Rigidbody.MovePosition.html) and definitely check what type of collision detection you are using (Discrete/continuous etc) , as teh default collision is good for basic stuff, not so much when things get a bit more complicated

olive ridge
#

le issue: it seems that whenever i move circles it seems that theyre too stupid to realise that their target circle's position also changes relative to them and ends up causing what you see in the video, how do i fix it?

#

the relevant code for it is this

    {
        List<Vector3> points = new List<Vector3>();
        float circumferenceProgressPerStep = (float)1/sides;
        float TAU = 2*Mathf.PI;
        float radianProgressPerStep = circumferenceProgressPerStep*TAU;

            for (int currentStep = 0; currentStep < sides; currentStep++)
            {
                float currentRadian = radianProgressPerStep * currentStep;

                GameObject dot = Instantiate(spawnDot, new Vector3(Mathf.Cos(currentRadian), Mathf.Sin(currentRadian), 0) * radius, Quaternion.identity);

                Vector2 Dpos = dot.transform.position;
                Vector2 Tpos = targetCity1.transform.position;

                anotherfuckingscript targetScript = targetCity1.GetComponent<anotherfuckingscript>();

                float distanceFromTarget = Vector2.Distance(Dpos,Tpos);
                
                    if(distanceFromTarget < targetScript.radius)
                    {
                        float angle = Mathf.Atan2(Tpos.y - Dpos.y, Tpos.x - Dpos.x) * Mathf.Rad2Deg;
                        dot.transform.rotation = Quaternion.Euler(0,0,angle);
                        float distanceFromRadiusEdge = Mathf.Abs(distanceFromTarget - targetScript.radius);
                        dot.transform.Translate(-distanceFromRadiusEdge/2f, 0f, 0f, Space.Self);
                    }

                points.Add(dot.transform.position);
                Destroy(dot);
            }
        return points;
    } ```
vestal arch
#

what's the expected behaviour? that the unmoved circle stays the same?

olive ridge
vestal arch
#

you're leaving out quite a bit of context here
what would "deforming properly" be? which is the target?

olive ridge
#

ok, so i decided to see where the said vertices spawn and it seems they dont move with the circle

olive ridge
vestal arch
#

so the unmoved circle is deforming correctly, but the one you're moving should also deform in a similar way?

olive ridge
#

ok yeah you dont know what i want

vestal arch
#

yeah im not psychic lol

#

is getCircumferencePoints the function that generates the circle? check where it's being called from

karmic sand
#

Im trying to make procedural terrain and its working fine when i have no falloff but if i do then the X axis works fine and the chunks for it line up but the Y(Z) axis has massive gaps between the seams and i cant seem to figure out why that is. i can provide more code if needed but i think its an error in this code here somewhere.

#
float[,] heightFinalValues = new float[width, height];
for (int x = 0; x < width; x++)
{
    for (int y = 0; y < height; y++)
    {
        float noiseSum = 0;
        float maxPossibleVal = 0;
        for (int k = 0; k < heightMapSettings.noiseLayers.Length; k++)
        {
            noiseSum += noiseLayers[k, x, y] * heightMapSettings.noiseLayers[k].strength;
            maxPossibleVal += heightMapSettings.noiseLayers[k].strength;
        }
        int chunkSizeInVerts = meshSettings.numVertsPerLine;
        // Adjust based on chunk's world position (coord)
        int chunkOffsetX = (int)(coord.x * (chunkSizeInVerts - 1));
        int chunkOffsetY = (int)(coord.y * (chunkSizeInVerts - 1));
        // Falloff map's center
        int halfFalloffMapSizeX = fullFalloffMap.GetLength(0) / 2;
        int halfFalloffMapSizeY = fullFalloffMap.GetLength(1) / 2;
        // Calculate global indices with offsets
        int globalX = x + chunkOffsetX + halfFalloffMapSizeX;
        int globalY = y + chunkOffsetY + halfFalloffMapSizeY;
        // Clamp to avoid out-of-bounds access
        globalX = Mathf.Clamp(globalX, 0, fullFalloffMap.GetLength(0) - 1);
        globalY = Mathf.Clamp(globalY, 0, fullFalloffMap.GetLength(1) - 1);
        float falloff = fullFalloffMap[globalX, globalY];
        float baseHeight = heightCurve_threadsafe.Evaluate(noiseSum / maxPossibleVal) * heightMapSettings.heightMultiplier;
        heightFinalValues[x, y] = baseHeight * falloff;
        if (heightFinalValues[x, y] > maxValue)
        {
            maxValue = heightFinalValues[x, y];
        }
        if (heightFinalValues[x, y] < minValue)
        {
            minValue = heightFinalValues[x, y];
        }
    }
}
return new HeightMap(heightFinalValues, minValue, maxValue);
#

heres an image of the issue

glossy ledge
#

What am I missing here?
I am trying to draw a line (using linerenderer) in the inverse direction of the touch position, which in and of itself works, but as the video shows for some reason I can only draw it from the world origin if I want the linerenderer to stay "flat"(so no banking) , or draw it from the right position but getting back that annoying rotation stuff.

The code is in the video and here as well:
https://pastebin.com/TpiUuVwF

cold parrot
wide bobcat
#

im using unity 2D and i dont get what i did wrong here, stafield not even showing up in the front no matter what i did

#

i've tried for almost 2d now and dont understand why it isnt showing up

wide bobcat
#

where can i actually get help

#

from that

karmic sand
cold parrot
#

i would check all + operations

wide bobcat
#

what is the proper channel for help for what i need

wide bobcat
#

alr thanks

devout ruin
#

Hi! I have a silly question, I use the fbx exporter to export my various Unity assets to FBX. However, when I select my 400 assets and export them all at once, they will all be in a single .fbx file. My question is: can I export them all at once, but have them all be independent (one .fbx per asset, as if I were exporting them individually)?

I've coded a Python program to automate some mesh modifications on Blender and I need them to be individual .fbx. Thanks 😉

dire pelican
#

!code

tawny elkBOT
cold parrot
steady bobcat
cold parrot
#

but you wont have an FBX 😕

steady bobcat
#

if its just to edit in blender and then re export i dont see a problem

devout ruin
devout ruin
steady bobcat
#

well do whats best for you, its another option

quartz sun
#

Hi I'm trying to create a wall jump mechanic but i think I'm going about it the wrong way? Here is my code:

steep herald
#

@quartz sun Vector2.left is (-1, 0), Vector2.up is (0, 1)

By multiplying the vectors, ur scaling 1 vector's components by the other.

x => -1 * 0 = 0,
y => 0 * 1 = 0
result (0 ,0)

#

and then it doesn't matter what you scale the vector with

quartz sun
#

The player movement is better now but there is the issue now with the updated code I added which makes the jump very rigid

steep herald
#

So when youre applying an impulse, you dont scale with the delta in time. It's not a continuously applied force, it's a response to an action that should be consistent across all occurrences of that action.

Here, even scaled by the dt(and it shouldn't be) the impulse is still very large. You need to reason about the final value of that impulse and how it'll affect your movement.

sweet fulcrum
dire pelican
#

I'm trying to make this building area but my current method of collision detection is pretty dumb. I'm just drawing a ray from the camera to the cursor and setting the position of whatever object I'm holding to the intersection between the ray and other objects

#

And that's leading to stuff like this where one object clips inside another. How would I go about fixing this?

#

I could do something along the lines of- inch the object I'm holding forward in the direction of the ray starting from the camera until it touches something, but that sounds inaccurate and pretty annoying. Is there a better way?

#

Turns out sphere/capsule casts are a thing. Thanks anyways

cold parrot
dire pelican
cold parrot
dire pelican
#

That's fair.

cold parrot
#

Float solutions are just using a grid that scales based on number size and is unpredictable

dire pelican
#

That makes sense

whole sorrel
#

Is there a cheat sheet for what type of level procgen algorithm to use depending on the use cases?

unkempt meadow
#

How is it possible that my coroutine gets called multiple times even when the first lines of the IEnumerator are flipping the higher and lower bools?:

if (lowCrawl && lower &&!higher &&!transitioning)
{
higher = true;
lower = false;
StartCoroutine(GetHigher());
}

dire pelican
vestal arch
unkempt meadow
#

The question is why should the coroutine be called again when higher is true and lower is false?

vestal arch
#

where are you resetting them back to higher = false or lower = true

vestal arch
#

also maybe you have multiple of this component, whether that's on purpose or not

unkempt meadow
unkempt meadow
vestal arch
#

where else are lower/higher getting set?

unkempt meadow
#

oh my god I'm a moron

#

nvm fixed

#

it wasn't that, it was something stupider than that

cold parrot
unkempt meadow
#

I want to check whether the tunnel in front of my is getting narrower. So far I'm sending two rays, one higher than the other, towards move direction

If the higher ray hits and lower doesn't, that's a positive result for me...but that's very unreliable. How can I improve this?

For example, I could extend the distance of the rays and compares the distances between the two hits AND check surface normal angle for better certainty.

Is this better? Anything else?

chrome sage
rugged storm
#

how would i add sound effects to UI, navigation? like more specifically i guess how do i detect the event system switching selected UI elements, i can figure out the playing sounds part

leaden ice
rugged storm
#

also another issue is i notice that what ever UI is selected, gets deselected when clicking, how do i disable this or reselect when a controller input is detected or something?

leaden ice
#

It's a setting on your input module

rugged storm
#

tysm!

#

Yo does unity have godot like autoloads? Or only normal singletons?

night harness
#

There’s no official implementation of that but you could recreate it in a couple different ways

rugged storm
cosmic rain
rugged storm
#

Besides the ones on the starting scene the rest are for the editor ofc, a autoloads system like godots would eliminate the need for that

cosmic rain
winter crescent
#

i got a error message saying i need a animator conponment, what does that mean

winter crescent
swift falcon
#

I want to create a separate object that I can use in multiple classes derived by mono behavior. I have been looking for references relevant to that. It's poco, something we use in normal c# programming.
I have an idea how to code it but Monobehavior restricts a lot of it.

leaden ice
cosmic rain
# winter crescent

This sounds like something related specifically to VR chat, so you should ask in their community. !vrc

#

!vrchat

tawny elkBOT
leaden ice
swift falcon
#

That's what I have been trying to figure out.

leaden ice
swift falcon
leaden ice
#

I answered it

#

There is nothing preventing you from doing anything you do in "normal C# programming" in Unity

swift falcon
#

perhaps if I share my code you'll understand what specifically I am trying to achieve?

leaden ice
#

that would be great

#

I don't understand what you're asking

#

what do you mean by "my code breaks"?

#

Also are these snippets from two different classes?

#

You didn't share what any of this is: RockPool.rockPoolInstance.GetPooledGameObject();

#

so it's hard to tell what that;s calling

swift falcon
#

this is the same class

leaden ice
#

or what's going wrong

#

so what do you mean by "my code breaks"?

#

What are you expecting to happen and what actually happens?

#

It might be helpful if you made a thread

swift falcon
#

okay

swift falcon
# leaden ice It might be helpful if you made a thread

I think I figured it out, thank you. This was a confusing question to ask even for me. This was do-able but we don't normally think about scalability unless it is a big project, so maybe that might have confused everyone when I asked if they know any references for SOLID.

#

thanks again.

#

if you initialize it in the same FixedUpdate, it will keep refreshing the index

leaden ice
#

I'm gonna be honest, I still have no idea what you were asking here.

swift falcon
#

but you at least made effort to understand and try to help me out, even if you were clueless, so I thanked you for that. I left a code up there, it might help, because it is working now. The problem was setting the values once every time the timer is 0. When I tried it it started refreshing index but it wouldn't give me the error or anything.

#

if you still like me to move this to thread, I'll do that.

lean sail
swift falcon
#

I am not going to keep on repeating myself if you guys don't understand you guys don't understand. Lets just leave it at that.

#

line 41 is ShootSytem.play(); and gunscriptable object is the glock model it says i have an error while shooting my gun and i dont see any errors

swift falcon
#

you need to initialize your gun

#

or the game object that you're trying to use here.

lean sail
# swift falcon how is it questionable?

Well for one, the hardcoded GameObject.Find calls in a row. But since you've deleted it I cant answer more...
As for ur 2nd message, people are trying to help, the way you've worded questions are extremely vague and just generally dont make sense. Repeating it or saying you wrote it above doesnt help yourself get help.

swift falcon
swift falcon
# lean sail Well for one, the hardcoded GameObject.Find calls in a row. But since you've del...

Oh that, it is wiser to get the objects from your game scene or from the resources. Thankfully I didn't post my object pool code where I am getting prefabs from the resource folders. The second message was I was looking for a way to initialize an object once and reinitialize an object when the timer runs out without using any coroutines because coroutines is an expensive call, or so I've heared.

#

so I asked here if anyone have any reference or a site or even a section of this community that has any remote reference of pocos being used to code in unity.

lean sail
swift falcon
lean sail
#

In regards to your coroutine part: Using a timer vs a coroutine is fine here. I doubt you'll ever run into issues with coroutines here. Youd really have to be starting a lot of them to see a performance difference. The profiler would give you more insight to these things too

lean sail
#

Cycle through them with a random index isnt related to the whole Resources vs drag and drop

swift falcon
#

interesting

#

in that case maybe I am asking questions that no one here ever heard of, makes my questions sound vague.

night harness
#

sounds like a pretty standard question

swift falcon
lean sail
#

The code you deleted above literally had line by line GameObject.Find to populate a list so I dont see how you're thinking dragging is worse here

night harness
#

Or depending on the context /type of content break that big list down into a list of lists

swift falcon
night harness
#

Yeah in most cases a ScriptableObject holding a list is preferable than resources

swift falcon
#

I got scared because bawsi said "your code is questionable" so I deleted it

swift falcon
#

Thank you guys for this discussion.

#
void Start()
    {
        rockSpawners.Add(GameObject.Find("rockSpawn1L"));
        rockSpawners.Add(GameObject.Find("rockSpawn2L"));
        rockSpawners.Add(GameObject.Find("rockSpawn3L"));
        rockSpawners.Add(GameObject.Find("rockSpawn1R"));
        rockSpawners.Add(GameObject.Find("rockSpawn2R"));
        rockSpawners.Add(GameObject.Find("rockSpawn3R"));
        rockSpawners.Add(GameObject.Find("rockSpawn1T"));
        rockSpawners.Add(GameObject.Find("rockSpawn2T"));
        rockSpawners.Add(GameObject.Find("rockSpawn3T"));
        rockSpawners.Add(GameObject.Find("rockSpawn1B"));
        rockSpawners.Add(GameObject.Find("rockSpawn2B"));
        rockSpawners.Add(GameObject.Find("rockSpawn3B"));
        time = 500f;
        index = Random.Range(0, rockSpawners.Count);
    }

    void FixedUpdate()
    {
        time--;
        if(time == 0)
        {
            Debug.Log("TIME IS: " + time);
            index = Random.Range(0, rockSpawners.Count);
            spawnerTransform = rockSpawners[index].transform;
            rock = RockPool.rockPoolInstance.GetPooledGameObject();
            ReInitObject(index, spawnerTransform, rock);
            time = 500f;
        }
    }

    void ReInitObject(int index, Transform spawner, GameObject rock)
    {
        PooledObject currentPooledObject = new PooledObject();

        currentPooledObject.currentIndex = index;
        currentPooledObject.currentRockSpanwer = spawner;
        currentPooledObject.currentRock = rock;
        
        if(rock != null)
        {
            currentPooledObject.currentRock.transform.position = currentPooledObject.currentRockSpanwer.transform.position;
            currentPooledObject.currentRock.transform.rotation = currentPooledObject.currentRockSpanwer.transform.rotation;
            currentPooledObject.currentRock.SetActive(true);
        }
    }
#

Here is the code bawsi, have at it.

lean sail
swift falcon
#

is GameObject.Find("object") is an expensive call too?

rigid island
#

it has to scan all objects , also string are very error prone

lean sail
# swift falcon is GameObject.Find("object") is an expensive call too?

You probably wont notice any lag from this but it's definitely relatively expensive. Since this would be searching the entire scene compared to already having the reference.
Its better to avoid it because its fragile. If the name of the object ever changes 3 months later, suddenly this code stops working and you'll be wondering why

swift falcon
#

never actually thought of it this way, I only thought "what if you were to select 100-1000 objects"

#

Thank you guys

night harness
#

Also if multiple objects have that name

wild nebula
#

Anyone familiar with using list for localization?

I need to pass down list to an argument, I assume its done this way?
{0:list:{typeName}: {fromValue} -> {toValue}|\n}

Right now I am trying to make item description from these.
Example description:
Damage: 5 -> 7
Agility: 3 -> 5
Defense: 1 -> 2

I have a struct with Enum StatsType, float fromValue, and float toValue.

So I have a List<StatOptionDescription> that I can pass down to.
But I am not sure how to properly pass them down so that it can work with LocalizedString.

hasty canopy
#

Hello, does Unity's playable API support target matching?

quick elbow
#

Anyone know how I can enable nullable for just my scripts? I'd like to get warnings in both Unity and Visual Studio

young yacht
#
void Start(){
        playerInput.UI.Click.Disable();
        playerInput.Player.Disable();
        playerInput.UI.Disable();
}

does anyone know how to disable mouse clicks? i have this main menu and everytime i start the game and click with the mouse it deselects the button selected

last quarry
#

How is a single LogStringToConsole call taking 60 milliseconds?

quartz folio
last quarry
#

So this goes away in a release build?

quartz folio
#

Not if you've got stack traces enabled

#
#if !UNITY_EDITOR && !DEVELOPMENT_BUILD
      // Remove stack traces for Debug.Log and Debug.LogWarning.
      // If something is important enough for traces it should be an error or exception.
      Application.SetStackTraceLogType(LogType.Log, StackTraceLogType.None);
      Application.SetStackTraceLogType(LogType.Warning, StackTraceLogType.None);
#endif
last quarry
#

Thanks, that makes sense

unkempt meadow
#

Although what I added seems to be working fine for now

#

But I should maybe replace rays with capsules

regal crag
cosmic rain
regal crag
#

my computer is so potato

#

ffs give me a bit more time

mossy wedge
#

can someone make this make sense to me?
Code snippet:

        Debug.Log($"Keys in playerGameObjects: {string.Join(", ", playerGameObjects.Value.Value.Keys)}");
        Debug.Log($"ContainsKey({LocalClientId}): {playerGameObjects.Value.Value.ContainsKey(LocalClientId)}");
        Debug.Log($"playerGameObjects.Value is null: {playerGameObjects.Value == null}");
        Debug.Log($"playerGameObjects.Value.Value is null: {playerGameObjects.Value.Value == null}");

        if (playerGameObjects.Value.Value.TryGetValue(LocalClientId, out var player))
        {
            Debug.Log("Entry found");
            localPlayer = player.MapToANetworkObject().gameObject;
        }
        else
        {
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.AppendLine("Player Remapping Failed");
            stringBuilder.AppendLine("Context dump: ");
            stringBuilder.AppendLine($"Local id {LocalClientId}");
            foreach (var item in playerGameObjects.Value.Value)
            {
                stringBuilder.AppendLine(item.ToString());
            }
            Debug.LogError(stringBuilder.ToString());

        }

Logs:
Keys in playerGameObjects: 0
ContainsKey(0): False
playerGameObjects.Value is null: False
playerGameObjects.Value.Value is null: False
Player Remapping Failed
Context dump:
Local id 0
[0, NetworkEntityRef]

cosmic rain
mossy wedge
#

i am trying to access a dictionary by TryGetValue with the key LocalClientId, but the TryGet fails and logs the remapping failed, but the logs do indicate that the LocalClientId (0) is present

cosmic rain
quartz folio
#

What type is the ID?

mossy wedge
#

ulong

#

and the key is a custom struct

quartz folio
#

Well that seems likely to be the issue

mossy wedge
#

whats wrong?

quartz folio
#

Have you implemented GetHashCode and Equals appropriately with your struct?

mossy wedge
#

no

quartz folio
#

Is your struct simply a wrapper on your ulong?
If you're using it as a key to a set you should override both of those methods for performance reasons anyway

mossy wedge
#

ye it wraps a ulong i use to track objects (with some utility functions)

cosmic rain
#

I'm not sure why you think a ulong would be equal to a struct then.

#

But anyways, I'd start with debugging the code with a debugger.

mossy wedge
#

implemented those functions and now stuff works

#

Thanks for the help

regal crag
#

but the maths work out logically

#

another point might be my code blocking people from riding slopes

#

and the maths there didn't work out

#
                {
                    // check to see if player is in same direction as the resultant velocity
                    if (Vector3.Dot(movementForce, currentVelocity + movementForce) > 0f)
                    {
                        // get the normal of the obstruction
                        var obstructionNormal = Vector3.Cross
                        (
                            motor.CharacterUp,
                            Vector3.Cross
                            (
                                motor.CharacterUp,
                                motor.GroundingStatus.GroundNormal
                            )

                        ).normalized;

                        // prevent movement force that would boost the player
                        movementForce = Vector3.ProjectOnPlane(movementForce, obstructionNormal);
                    }
                }```
#

so presumably i either flipped a vector here or the ProjectOnPlane actually accelerated the player

#

when i was sliding upwards

#

my deduction is since the code only have problem when I slide upward, the vector here is wrong

cosmic rain
#

Project on plane can't produce a vector with bigger magnitude than the input vector.

regal crag
#

I used some debug rays and did find out that the magnitude was much larger than expected, which confused me when I reviewed the code

#

can't seem to pinpoint where it got wrong even with breakpoints

cosmic rain
regal crag
#

I'm trying to get the normal of the obstruction so the player wouldn't slide upwards by spamming the slide button

cosmic rain
#

I don't see anything related to obstructions in it though. Only ground normal and character up.

regal crag
#

whenever when the player isn't grounded (is not stable on ground) but still find ground (obstruction)

cosmic rain
#

You should probably visualize the related vectors in the game to see if they match your expectations

#

Or as I said earlier, step through the code and see if the values match your expectations

regal crag
#

I'll try again and see if the grounding normal has any problems

azure frost
#

So, I'm working with a modified Kinematic Character Controller, and I used it's "Charging" tutorial to make a Rolling ability.

https://assetstore.unity.com/packages/tools/physics/kinematic-character-controller-99131?srsltid=AfmBOop1MQShdPTUeQwhp7wgt997XCZpNYBhj53IB21WHlD1f6iriIT-
(This is the thing.)

Get the Kinematic Character Controller package from Philippe St-Amand and speed up your game development process. Find this & other Physics options on the Unity Asset Store.

#

However, the whole ability is quite bork'd. And it has strange interactions with Water.

#

And here's what happens when I try rolling into it.

But curiously, it ONLY happens the first time I enter water, and ONLY when rolling into it.

#

And here's the error that comes up.

somber nacelle
#

show code

azure frost
#

Should I just post the C# files wholesale?

somber nacelle
#

!code

tawny elkBOT
somber nacelle
#

wait, it doesn't even seem to be your code, the error points to example code from the asset

azure frost
#

If I need to post the motor script as well, let me know.

somber nacelle
#

_waterZone is null there. i'm not going to comb through code that isn't even yours to find out why it might be null though.

azure frost
#

Okay, I have turned "private Collider _waterZone;" into public.

The water zone appears to be whatever water volume the player is currently swimming in. And somehow, Rolling causes the player to enter the swimming state without getting an assigned water zone.

junior flicker
#

the slightly blue cells should be way more blue basically, if they weren't affected

leaden ice
#

Doesn't seem code related

junior flicker
#

partly, but you're right it's mostly visual I'll move this, thank you

azure frost
#

Okay, I fixed my problem. I just had to update the water detection function to be extended to all states that weren't swimming.

cosmic rain
safe flame
#

hey yall, losing my mind over what i "think" is code logic again:

The idea behind what i'm trying to do is to make the camera fade to black during the monster's kill animation, however the fade never happens for some reason and you can see the void as the player is being teleported back to the beginning

I've verified that the camera DOES fade if i change the priority within inspector, and the player.FadeToBlack() function is also called during runtime

The flow of the script goes:
Player is killed, monster's kill animation starts
-> during the monster's kill animation, it calls ResetMonster(), which just makes it so that it's not triggering the player kill multiple times, but also invokes the GameOver() event for the game manager
-> Gamemanager tells player to fade to black (change priority of the fadetoblack camera on the player), then triggers an event to reset the game
-> Roommanager.RestartRoomManager() is called, which teleports the player and monster back to their beginning positions
-> player.RespawnPlayer() is called, sets fadetoblack back to 0 so the camera should be in its normal state

https://paste.ofcode.org/QQdgJLazdUCiZBt9jh6gUW

somber nacelle
#

the issue is likely that you're changing the priority to 2 and then back to 0 all within the same frame within the same method chain so nothing else is happening during that time that the priority is 2

#

you don't want to set it back to 0 until after the transition

safe flame
#

Ok ok, I'll take a look at what i can do

safe flame
somber nacelle
#

and that all happens within the same frame.
Imagine this scenario:
I have a $5 bill, you want this $5 bill to buy a drink from a vending machine. I then stop time, place the money in your hand, then immediately take it back and resume time. Were you able to spend that $5 at the vending machine?

#

This is essentially what you are doing with the priority for the camera, there is no time that passes between when you set it to 2 and when you set it back to 0

safe flame
#

Oh yeah I understand that, I mean how do I make the time flow "as intended", I thought maybe coroutines would've helped but no dice

somber nacelle
#

wdym "no dice"? that definitely would work provided you actually wait in the coroutine

#

otherwise, you might need to unspaghettify your code and use some more events (like an event that triggers when the transition is complete)

safe flame
#

Alright, I might've screwed up with the coroutine placement when I tried, I'll take a look again

I also did spend quite a bit of time unspaghettifying the code (it was way way worse than this lol), but I'm not against doing more of that

#

Though i might ask assistance regarding that when the time comes, the current state of the codebase is as much as I could do

naive swallow
safe flame
#

tried to go up some stairs and Dio kept placing him back down

#

being on topic, not sure what i did before with my coroutine, but i got some form of progress now

quick elbow
chilly surge
#

The csc.rsp part will get Unity to compile with NRT.

#

For VS/VS Code, I use a Directory.Build.props file:

<Project>
  <PropertyGroup>
    <Nullable>enable</Nullable>
  </PropertyGroup>
</Project>

I don't know if Rider respects it or not.

#

(Instead of Directory.Build.props you can also use an editor script to modify the generated .csproj files, but that's a lot more work for the same result)

heady iris
#

I have a List<TrackInfo> here. TrackInfo contains a number of [SerializeReference]-attributed fields. All of them have field initializers, but when I add an item to the list, everything starts out null anyway.

I added that "huh" field to check that default values work at all. It's a regular int field, and that works fine.

I also checked that field initializers work for [SerializeReference] fields that aren't part of an object stored in a list, and that works fine too.

#

I guess I'm going to need to add a button to the inspector that adds an item to the list and populates its fields

zinc flax
#

I think unity particle is broken because I forced every Z axis of my particles and they ALWAYS drift away from camera in Z axis!!!

Only solution I found was fixing their Z axis inside shader in vert function... But this is not an actual fix.
https://pastebin.com/cKZ1cmTY
what is going on here??? Why are they always drifting away in Z axis? This is stupid...

quick elbow
chilly surge
#

Where are you putting the file?

quick elbow
#

@chilly surge At the root of my assembly

#

I have an asmdef at the root of my assembly in a folder. I put the csc.rsp and the Directory.Build.props next to the asmdef

chilly surge
#

Hmm I'm not sure that work, I think the file has to be on the same level (or above) the .csproj file.

glossy ledge
astral fiber
#

when I am in a scene and I look at the Scene view, the text looks perfect, not blurry at all, but when I go into game it has like weird rectangles around the letters. I tried increasing padding to 10-15-20pixels but it fixed the rectangles but it made the letters feel weird like choppy, in the scene it looks decent but at the game the letters are like low quality, anyone knows a fix?

hexed oak
#

If I have an event that is supposed to trigger at frame 10 of a video playing, but the video happens to skip frame 10, is there a way to try and make sure that event is hit anyways?

zinc flax
#

has anyone else had problem with particles velocity? Im creating a 2D game using meshes and creating particles with meshes. I completely locked their Z position everywhere even added a Z clamp in update for every particles. I also tested disabling any velocity completely. Particles always drift away from camera in Z axis no matter what!! im getting frustrated , I have been trying to solve this the entire day.

hexed oak
zinc flax
hexed oak
#

I'm trying to cover if arbitrary frames are skipped, not specifically frame 10.

zinc flax
#

so you need to detect for any frame skip happening?

hexed oak
#

yep

zinc flax
#

then do something like this:

float expectedFrameTime = 1f / 60f;
float skipThreshold = 0.005f;

void Update()
{
float delta = Time.unscaledDeltaTime;

if (delta > expectedFrameTime + skipThreshold)
{
    Debug.Log($"Frame skipped. Delta time: {delta:F4}");
}

}

hexed oak
#

what does your emission collider look like

bronze maple
#

im not to sure on where to go to ask for help for this im starting to get into some sort of developing and trying to run this starter project file i have to test out movemtn/animations etc but i cant get it working due to error codes i dont know how to fix if anyone could help it would be great

#

its these 4 errors here

zinc flax
last island
#

I'm unsure, using the InputSystem, how to read if any mapped action is in use or not. I tried "IsPressed()" but it returned true all the time. So tried something else instead which always returns false.

private static bool GetAnyActionHeld()
{
    foreach (InputAction action in InputSystem.actions)
    {
        bool? state = (action.ReadValueAsObject() as bool?);
        if (state.HasValue && state.Value) return true;
    }
    return false;
}

Is there a better way? I can't imagine that Unity made this system without a way to check if any input is in use (Like for "Press Any Key").

last island
#

So I have a Credits scene where when you have held any action mapped button for x amount of time, then the credits will prematurely end.
So it needs to be that I can read any of the input actions I have in my maps and check if any of them are in use. If they are, I can assume a button is being held down.

#

I'm open to suggestions on doing this differently, if there is a better way to approach that problem

leaden ice
last island
#

Oh that's handy

#

So GetAction() but with that instead?

#

Or "FindAction" I guess.

leaden ice
#

Or perhaps "<*>/*[Button]" for any button control

leaden ice
last island
#

InputAction action = InputSystem.actions.FindAction(@"<*>/*[Button]");
So instead of this, how would I then prompt the InputSystem to figure out if a button indeed was pressed?

#

Or is being held, I guess

leaden ice
#

Make an action in your asset of type Button
Make a binding for it, and use <*>/*[Button] as the binding path

#

then treat in in your code like any other button action

#

so like InputSystem.actions["MyAction"].IsPressed()

#

or give it a Hold interaction

#

and listen for WasPerformedThisFrame()

last island
#

So instead of "InputHelper.GetButtonDown("Exit Credits")" I would do "InputHelper.GetButtonDown("<*>/*[Button]")

leaden ice
#

no

#

I don't know what InputHelper is

#

that's a custom thing you made, so it's hard for me to say how to use it

last island
#

Ah yeah, sorry that's a utility class. Forgot about that.

#

So this is what the code currently does to see if a specific action is being called

public static InputAction GetAction(string action)
{
    InputAction inputAction = InputSystem.actions.FindAction(action);
    if (inputAction == null)
        Debug.LogError($"The InputAction \"{action}\" doesn't exist. Check if the spelling is correct or if the action exists in Project Settings -> Input System Package.");

    return inputAction;
}

So for example "Settings Menu" might be an action that is then passed on to this method via the InputHelper class.
It then returns the InputAction object, if any, so that you can perform things on the action like reading from it.

#

In my scenario, I need to be able to read if any mapped button is being held currently, so that I can advance a timer while the buttong is being held.

leaden ice
#

It would be this way then InputHelper.GetButtonDown("Exit Credits")

#

But in the input asset, you would bind the Exit Credits action to <*>/*[Button]

last island
#

Aah, okay. I getcha.

#

Sorry for the confusion there. I think I got it now.

#

It is odd to me that Unity does not have an easier way of doing that, but there is likely an implementation detail as to the why.

leaden ice
#

I mean, I feel that's pretty easy

#

maybe a better shortcut for it in the UI is needed

last island
#

I feel like InputSystem.IsAnyButtonHeld() would be the easiest

#

Rather than having to assign an "Any key" like this

steady bobcat
#

The point of inputsystem is to move away from doing keyboard only stuff

last island
#

Sure, although I don't see what that has to do with what I am envisioning

#

Controllers also have buttons

leaden ice
steady bobcat
last island
steady bobcat
#

blah blah unity not wanting to presume or overstep with such a function blah blah

last island
#

I doubt it's that. They had in the old input system if I'm not mistaken.
I think it was simply overlooked in the new design when it was made.

#

Just odd after this amount of time 🤷‍♀️

steady bobcat
#

I presume it was keyboard + mouse only but this new system is trying to make make us avoid being keyboard centric. Anyway you have to do whatever works yea its nice to wish for a nice solution to already exist

last island
#

And I want to point out again that, what I asked for is not keyboard centric

#

It is input method agnostic. Every input has buttons of some kind.

old elk
#

Yeah, the new input system is...missing quite a few things that seem like common sense

#

I suppose that in the code for your event handling, you could just route the InputAction.CallbackContext into a custom input handler and have that increment a value if context.performed/decrement that value if context.canceled, then check if any button is held by querying that value. It's a bit like a counting semaphore lmao

#

is it legwork? yeah, you have to make sure you slap that method call into every event handler. could be worse though

leaden ice
#

Yeah that sounds... way more complicated than simply making a binding for all buttons.

old elk
#

Can you make a binding that just accepts "any button"?

leaden ice
#

Scroll up

#

you are about 15 minutes too late in the conversation

old elk
#

ah i see that

leaden ice
#

er, 30-40 minutes

old elk
#

my bad, I missed that lmao

cold parrot
last island
old elk
#

the other time was actually brought up in a thread some years back and one of the Unity devs said "yeah we're looking into this next" but it was never implemented lmao

leaden ice
#

Just because something is a relatively common use case doesn't mean it necessarily needs its own special API.
This is an input system.
Sort of like how Unity is a game engine, yet doesn't have a "First Person Shooter" module.
It's a general purpose system, and the API needs to be powerful and flexible, and yes, easy to work with, but if you over-opinionate your API you end up with a more complicated API with tons of caveats and multiple ways of doing the same thing.

old elk
#

right but

this isn't a "special API", this is just "is any button held"

leaden ice
#

that's a special API call

old elk
#

i think we have different ideas of what consitutes a "special API" then

leaden ice
#

¯_(ツ)_/¯ seems that way yes

spare dome
#

Would anyone happen to know how I can find how far a ray intersected a Gameobject?

leaden ice
cold parrot
last island
#

You could argue that any convenience call, of which the InputSystem has many, would be a "special API call" by your own definition, which to me would be an absurd notion.

naive swallow
leaden ice
naive swallow
#

If I'm making a "Press any button to continue" menu, do I want it to continue if the user moves their hand at all?

#

Probably not.

last island
old elk