#archived-code-general

1 messages Β· Page 449 of 1

rigid island
#

I just realized I do have 9.0 DLLs in my StreamingAssets, how do I make Unity ignore those for the editor ? I just need them when exporting the game

steady bobcat
#

in editor you can pick what platforms managed or native libs are used on

rigid island
steady bobcat
#

select it and check the inspector

rigid island
#

I guess this has something in the CsProj file?

steady bobcat
#

Its probably because they are in streaming assets that normal options are there? Are you loading these in yourself?

rigid island
#

(it just starts a .net core api server)

#

everything works fine except getting these annoying "errors" in IDE lol

steady bobcat
#

then lets presume vs code is dumb and thinks this dll is to be used even though unity wont

rigid island
#

Yeah I think you're right.. VSCode might be getting confused from the .csproj putting those dlls in the file

steady bobcat
#

tbh this doesnt even need to be in streaming assets if its just something you manage out of unity

rigid island
steady bobcat
#

yea but you can surely write your own automation to copy a file next to the build output

rigid island
#

hmm true maybe this is one of those convenience coming with this weird quirk to get around

steady bobcat
#

see if visual studio does this or if you can exclude the file yourself in vs code (though may return when unity regens things)

rigid island
#

yeah will give that a shot, thanks!

#

I wish there was some type of property I could use to ignore these in IDE :X

stiff mirage
#

I'm having an issue where my unit's shooting will slowly start becoming in sync with eachother. They shoot automatically on a timer 2.5 times a second.

Here's my firing code
https://paste.mod.gg/kyggkxkhimfl/0

Heres at the start and after like 2 minutes (Left is after 2 min)

Sorry if I asked this wrong, first time asking a coding question here

astral lotus
#

How can I start learning C# and learn using Unity?

rigid island
buoyant marten
#

Hey, can anyone help me, im trying to do a 3rd person aim system and i managed to do it but the player shakes/jitters the more i move around, apparently i have a mismach with fixedupdate physicks and lateupdate cinemachine camera and aiming

astral lotus
rigid island
rigid island
stiff mirage
#

Yeah they sync together lol

rigid island
#

yeaaah ok I think i watched the first video thinking thats AFTER

stiff mirage
#

Yeah I realized I uploaded them in the wrong order lmao

rigid island
#

I wonder if its somehow waiting on a specific frame to instantiate them

stiff mirage
#

I feel like it has something to do with adding to the timer not being continuous because delta time only gets added to the timer every time it runs through the script, causing each shot not to be shot at exactly 0.4 seconds.

#

and eventually they start linking up because of that? I'm not 100% sure how to explain that

#

would this be a fixed update thing actually?

rigid island
#

is it using shootTimer or burstTimer ?

stiff mirage
#

Shoot timer

rigid island
#

how does it shoot with shootTimer? I dont see if statements for that

stiff mirage
#

err

#

Wdym

rigid island
#
  void FiringLoop()
    {
        if (shootTimer < 1/stats.attackSpeed )
        {
            shootTimer += Time.deltaTime;
        }
        else
        {
            BurstLoop();
        }
    }``` like here
#

only BurstLoop seems to call Shoot() , kinda confused on that

stiff mirage
#

Oh ok
When shoot timer is greater than (for this unit 0.4), it call burst loop every update loop
When burst timer is greater than (for this unit 0), it shoots a bullet
When the burst amount is equal to the number of bullets in the burst (for this unit 1), shoot timer is reset to 0, restarting the loop

#

Ok it looks like swapping everything to fixed update and fixeddeltatime has fixed the problem

#

Thanks for taking a look at it !

buoyant marten
leaden ice
buoyant marten
#

yes

leaden ice
#

Then #2 is your issue

#

YOu cannot rotate the Transform directly or interpolation on the RIgidbody will break

#

Never touch the Transform for a Rigidbody

buoyant marten
#

interpolation helps a little, if i disable it the shake gets worse

#

ok any suggestions how can i do this better

leaden ice
#

rotate via the Rigidbody instead

#

i.e. rb.rotation = ...

buoyant marten
#

so add rotational force

leaden ice
#

I didn't say that

buoyant marten
#

oh ok

#

so to clarify the issue lies in the playermovement script where im rotating the player

#

so the gunaimer and aimingreticle are correct?

leaden ice
#

I don't know. I saw what is definitely an issue in the rotation. I'm not going to rule out other issues in other scripts.

buoyant marten
#

ok

PlayerRB.rotation = Quaternion.Slerp(PlayerRB.rotation, targetRotation, turnSpeed * Time.fixedDeltaTime);

i was thinking this then.

leaden ice
#

Start with:
PlayerRB.rotation = targetRotation; at first

#

just to rule out any issues with your Slerp

#

You are using a classic "wrong slerp" after all as well.

buoyant marten
#

thank you :) i'll dive into this

buoyant marten
#

hmm i should still use the late update for the gun aiming and reticle placement and fixed update for physics, correct?

leaden ice
#

yes

buoyant marten
#

ok thanks :)))))

hexed pecan
austere solar
#

anyone know the SQLite4Unity library? i wanna implement a function to update the db when a user starts a newer version of the game, and there seems to be no function for ALTER TABLE ADD COLUMN beside connection.Execute(string, object[])...

naive swallow
#

Is there a way to change the "Sample distance" of the float array passed to TerrainData.SetHeights? I have the terrain at the size I want (let's say 5000x5000) and a float array with some smaller number of points (say 1000x1000). Right now, it's setting the height of a corner of the terrain to what I have in there assuming the indices are 1 world unit apart. Instead, I want those indices to be "fractions of width" instead of "real space units". Like, heights[0,0] spans an area of 5x5 in real space, instead of 1x1, since the width of the terrain is 5 times the length of the array.

leaden ice
#

You could do it by accumulating mouse input in Update and using MoveRotation but that's extra work

#

Setting the rotation directly on the RB works

hexed pecan
#

I cant see their code on mobile so just assumed it is fixedupdate

hasty comet
#

Is there a clean way to convert a 2d color array to a 2d Texture? Feels like they should play nice but I'm not finding anything in the docs.

hasty comet
# cold parrot define "clean"

Generally fewest conversion of types as possible/ fewest loops as possible. Like I know I could probably loop through slowly coverting it to the 1d array for SetPixels but it feels like it should already be able to map 1-1.

cold parrot
hasty comet
#

ahh Very sad. I'll just run my own conversion to a 1d array.

fallen current
#

So - I've got an object moving, swaying side to side and up and down working really well, but I'm getting some weeeeeird jerky animation while walking/running, and my arms are disappearing.

Problem 1: I'm pretty sure this has to do with clamping the distance from the targetPosition GameObject (which is a fixed point attached to the camera). Has anyone dealt with that before? I think it might need smoothing? But I'm not 100% sure?

latent latch
#

I'd say it's probably related to childing the camera and translating the transform and having desync on what is captured. If you haven't already, try sticking the camera in late update (if you're moving the transform directly), otherwise check out cinemachine

tough flower
#

Hi hi ! I'm a complete unity newbie, and quite new to coding in general... If anyone is feeling gracious enough, could you lend a peek at my code ?

I'm making a result screen at the end of my level (for a rhythm game) and I'm wondering why it won't show up when music stops.

quartz folio
forest surge
latent latch
#

What's the error

lean sail
radiant gyro
#

Hey, I was wondering if anyone here could help me figure out how to do some fancy grid movement using AronGranbergs A* pathfinding utility, I'm trying to figure out how to get an agent with a 2x2 node/cell size moving correctly but the solution on his site hasn't helped much, it only works well for 3x3/odd sizes :/

forest surge
#

it was just weird and i couldn't find out what i did wrong lol

lean sail
lean sail
modern epoch
#

How do I activate my second pathfinder graph

#

I have all components on my object but it's not moving

radiant gyro
# lean sail usually its better to ask asset questions in chats/forums specific to that asset...

There's only a forum which I've tried asking on but I only got linked to this page which has code to get 3x3 size agents working but it doesn't work for even sizes: https://arongranberg.com/astar/docs/multipleagenttypes.html#grid-shape
I was hoping I might be able to find someone on here who might know although I'm aware it was a long shot.

robust lion
#
isGrounded = Physics.Raycast(transform.position, Vector3.down, groundCheckDistance + 0.1f, groundLayer);```

Im using this to check ground below the player. The problem with this is Raycast is very thin so if the platform is narrow or the player is on the edge of the platform then it wont Jump when im trying to jump.

I guess a capsulecast would be able to fix this? any ideas?
worldly hull
#

will u guys prefer single object pool or multi-object pool, one pool handle one object or let it handle all the pool object?

latent latch
#

one pool to one type

worldly hull
fiery steeple
#

@steady bobcat @somber nacelleI tried the same code as above ☝️ And now I don't have the error of yesterday anymore about the null reference, why is that ? πŸ€” I tried to press play multiple times to try to reproduce the "null" error of yesterday but nothing comes out πŸ€”

(this is the screenshot of today's code to make sure that I'm not crazy that it's the same code as yesterday)

somber nacelle
#

you're probably just getting lucky and the singleton's Awake is not being called before this object's OnEnable

steady bobcat
#

I think all Awake()'s should be called then OnEnable()''s

#

Or yea its pure luck, which can be fixed with changing the execution order

somber nacelle
#

https://docs.unity3d.com/6000.1/Documentation/Manual/execution-order.html

Awake is only guaranteed to be called before OnEnable in the scope of each individual object. Across multiple objects the order is not deterministic and you can’t rely on one object’s Awake being called before another object’s OnEnable. Any work that depends on Awake having been called for all objects in the scene should be done in Start.

fiery steeple
#

I pressed play around 10 times now, and still nothing πŸ˜„ I'm so lucky 🀣

somber nacelle
night harness
#

i think?

#

actually curious how that onenable inconsistency works in practice

somber nacelle
#

yeah the execution order typically does not change within the same editor session, i imagine that possibly restarting the editor can change it but i'm sure that regenerating the library would

night harness
#

that shouldn't be relevant for the thing you pointed out though right

#

probably related though? that doc isn't clear on the why's

somber nacelle
#

which script is executed first is 100% relevant to their issue, right now the singleton is executing first so they aren't experiencing the issue because they are now accessing it after it has been initialized

fiery steeple
somber nacelle
#

maybe

fiery steeple
#

Ok let me try that

somber nacelle
#

that is really just an assumption, but anecdotally it does seem to be the case

fiery steeple
steady bobcat
somber nacelle
#

relying on specifying the execution order is not a great solution because it just hides bad design choices. though since they've reverted their code to the previously broken state it seems like they no longer care about digging out of their spaghetti mess so whatever πŸ€·β€β™‚οΈ

night harness
#

defaultexecutionorder on a handful of select managers feels like a fair amount of tech debt to take on for the benefits in a smaller scale project

fiery steeple
steady bobcat
#

I personally init objects manually to control order but in this case it seems ensuring the manager executes first is the easy solution

somber nacelle
#

the easy solution would be to just make the events static like i pointed out yesterday. these objects are singletons so what is the point of using instance events instead of static events if they plan to just use a single instance of those objects anyway

fiery steeple
fiery steeple
#

but let me try again

somber nacelle
#

no you didn't because that issue is not possible if the events are static

fiery steeple
#

oh then I'm remembring wrong, or maybe there's was another issue when I used static πŸ˜„

somber nacelle
#

also the exception you've just shown doesn't even match up with the line numbers in the code you showed so wtf did you change this time

somber nacelle
#

oh actually, it's from a different script entirely, looks like it's from your singleton's OnEnable

fiery steeple
fiery steeple
somber nacelle
#

too many inter-dependent singletons notlikethis

fiery steeple
#

sniif πŸ₯²

#

How many Singletons should I have in a project ? πŸ‘€

somber nacelle
#

there is not a single answer to that. but when they all rely on each other you're just building the biggest pot of spaghetti that you can

fiery steeple
#

I must be italian then πŸ‘€ 🀣

#

though I don't understand that error at line 47 πŸ€”

somber nacelle
#

it's the same thing as the other issue

fiery steeple
#

oh ok

unkempt meadow
#

Guys, how the fuck do I set the light unit? There is no documentation.

All the ones suggested by intellisense are obsolete and don't work.

unkempt meadow
#

No, I mean unit

#

to make sure it's in lumen because I am experiencing some bugs with that

fiery steeple
unkempt meadow
#

intensity is set to a number higher than what I specified

unkempt meadow
#

it says it's deprecated

#

.lightunit

fiery steeple
unkempt meadow
#

I referenced hdAdditionalLightData but not the actual light

fiery steeple
#

ah

#

glad you solved it πŸ™‚

unkempt meadow
#

I don't get it

#

Using the Light and setting its intensity seems to be KIND OF a multiplier, but not really

#

I can't set the actual number in lumen

#

but for the HDAdditionalLightData, there is no method to set intensity that's not deprecated

#

I don't get it

fiery steeple
#

then I don't think it's the unit that you need but rather the intensity, but I think you need to define the unit first for Unity to know what units are we talking about

unkempt meadow
#

yes but

#

I'll show you

#

!code

tawny elkBOT
buoyant marten
#

'''
PlayerRB.AddForce(moveDirection * currentForce, ForceMode.Force);
''"

This causes my players body to also rotate which is not wanted, any tips on how can i do this better,

unkempt meadow
#
public class HeadlightIntensity : MonoBehaviour
{
    HDAdditionalLightData headLight;
    Light PointLight;


    void Start()
    {
        PointLight = GetComponent<Light>();
        headLight = GetComponent<HDAdditionalLightData>();
        PointLight.lightUnit = UnityEngine.Rendering.LightUnit.Lumen;

    }

    public void SetLightIntensity()
    {
        PointLight.intensity = 50f;
    }
}

Setting PointLight.intensity doesn't set it to that value.

However, there is no way to set headLight either intensity or unit. I don't get it

hexed pecan
unkempt meadow
#

and all other methods but I will test just in case

hexed pecan
#

Does it not say what to use instead?

unkempt meadow
#

but this actually works

#

so fuck intellisense

last quarry
#

Peak Unity experience.

#

I’d look at the actual code instead. Might be something in the comments about why it’s deprecated

unkempt meadow
#

On a related note, does anybody know how the fuck Light.intensity works? It's supposed to be a multiplier but it's...kinda not

stark stone
#

The Intensity of a light is multiplied with the Light color.

unkempt meadow
#

Oh wait, so that mean that the value of 8 is the default value set in the inspector?

#

if so, then I didn't need to do all this in the first place

stark stone
#

the default would be 1 i guess, not 8, because above 1 creates over bright lights i think

#

The value can be between 0 and 8. This allows you to create over bright lights.

#

this is what doc says

last quarry
#

This is HDRP right?

unkempt meadow
#

well that's the problem, it's not. Setting the light intensity to 1 gave me a value of 12 lumens while my default value is 50

#

and also, that also means that 8 can't be the default value either

#

so I don't know man

unkempt meadow
cosmic rain
#

Where do you see the lumens?

last quarry
#

There are three intensity values in HDRP. One is in Lumen, the next is a multiplier, the other is a multiplier for volumetrics.

#

The lumen one is handled by HDAdditionalLightData. I suspect the multiplier is the legacy intensity

unkempt meadow
last quarry
#

But for the most part you'd just interact with it via HDAdditionalLightData, which is the API for HDRP.

unkempt meadow
#

yea ok gotcha

unkempt meadow
#

I was wondering if there was a way using simply Light and using intensity, but I guess I can't get a precise result that way

last quarry
#

I see the first one as physically correct, the other two for artistic overrides

unkempt meadow
last quarry
#

Especially when you want to control brightness and volumetric brightness separately

modern epoch
#

Question, how do I activate my second pathfinder graph

cosmic rain
modern epoch
#

A star pathfinding

cosmic rain
#

Doesn't sound like something in unity by default

leaden ice
modern epoch
#

I didn't do anything tho

#

The second graph just doesn't work

leaden ice
#

Well I have no idea what you're talking about TBH

modern epoch
#

It's for a* pathfinding

leaden ice
#

You're going to have to provide way more details than that if you want help

modern epoch
#

Do you know the pathfinder component tho

#

Otherwise you can't help me

cosmic rain
modern epoch
#

It's built in

cosmic rain
#

Is it?

modern epoch
#

Yessir

cosmic rain
#

Then share a link to the documentation

modern epoch
#

U guys probably use navmesh

leaden ice
last quarry
#

This is A* Pathfinding Project?

#

I use it

#

I still don't know what a "pathfinder" component is πŸ˜„

modern epoch
#

Oh shit is it a project

cosmic rain
#

It's a third party asset

modern epoch
#

Lemme check

last quarry
modern epoch
#

OH

#

My bad

cosmic rain
#

Yeah, you probably should start with checking what you're using.πŸ˜…

modern epoch
#

It's been years since I've touched it

last quarry
#

From the question I think you may be referring to the graph?

modern epoch
#

Yes. I have 2 graphs

#

The first works perfect but the second is a bust

last quarry
#

You can't have two graphs active at the same time. So disable the first, then enable the second to switch

modern epoch
#

Ohhhhh

#

Ty sah!

shadow wagon
#

when I subscribe to something like this

    void Start()
    {
      _cursor.OnMouseDown += () => _cursor.SetPosition((Vector2)WristObject.transform.position);
    }```and this game object isnt ever going to be destroyed or disabled. Should I still unsubscribe?
#

I know if it was going to be destroyed then I'd have to do OnDestroy() { foo -= bar; }

#

but in testing, if Im going to play the scene, end playback, play the scene again, over and over again. will all those events remain subscribed?

somber nacelle
#

if the lifetime of both objects is the same then it likely won't matter at all but it is still good practice to always unsubscribe to events

#

the only time the subscriptions would persist would be if this were a static event (which doesn't appear to be the case) and you have domain reload disabled. still better to always unsubscribe though

steady bobcat
#

a subscriber component should un sub as it will still be invoked and prevent GC of the component and cause errors

shadow wagon
#

whats the correct method to unsubscribe in? OnDisable?

somber nacelle
#

if you subscribe in Start then unsub in OnDestroy

shadow wagon
#

cool!

steady bobcat
#

if you sub with a lambda then keep a ref to it to unsub it later.

somber nacelle
#

yeah that's a good point to bring up as well, even if you write the lambda exactly the same it's a different instance created so it wouldn't actually unsubscribe unless you cache the lambda in a field and sub/unsub using that field

#

or just subscribe using a method group

shadow wagon
#

I've cut out a lot of stuff that isnt relevant, is the way I'm using the event action good?

  public class Arm : MonoBehaviour
  {
    [SerializeField]
    CursorTarget _cursor;

    void Start()
    {
      _cursor.OnMouseDown += () => _cursor.SetPosition((Vector2)WristObject.transform.position);
    }

  }

  [Serializable]
  public class CursorTarget
  {
    public Vector2 Point;
    public event Action OnMouseDown;

    public void SetPosition(Vector2 pos) => Point = pos;

    void MouseDown()
    {
      OnMouseDown?.Invoke();
    }

  }```
steady bobcat
#

Good event but yea better to use a member function (to sub) as its makes unsubbing easier

shadow wagon
#

intellisense did it like that, which isnt what ive done in the passed, I normally use an event argument

vestal arch
#

wdym intellisense did it like that?

#

via a snippet, or..?

shadow wagon
#

whoops, i meant snippet

#

either way its not the way I'd typically pass a value into an event

vestal arch
#

i mean if MouseDown is supposed to be positioning Point (or i guess calling SetPosition), then it doesn't really make sense for it to be an event

steady bobcat
#

Probably better if CursorTarget or the pos is the first event arg.

vestal arch
#

this would probably be better with a supplier, imo

shadow wagon
vestal arch
#

think about what would happen if OnMouseDown was subscribed to by multiple classes, think about what that means
maybe that makes sense to you, but i don't know the context; from what ive seen i don't really think it does make sense

shadow wagon
#

that touches on something im still a bit unsure on, ive heard people say a class should never exist in a way that only one thing can use it

#

there will only ever be one Arm instance that uses this CursorTarget instance

#

(well, there will be two different Arms each with their own Target, but they dont communicate)

vestal arch
#

well, i'll ignore that specific restriction for flexibility, perhaps

#

but should CursorTarget be able to have multiple "sources", in a way?

hexed pecan
vestal arch
#

given that it only has one action, MouseDown

shadow wagon
#

its got _cursor.OnMouseRelease I ommited that as its called indentically to OnMouseDown

#
    void Start()
    {
      _cursor.OnMouseDown += () => _cursor.SetPosition((Vector2)WristObject.transform.position);
      _cursor.OnMouseRelease += () => _cursor.SetPosition((Vector2)WristObject.transform.position);
    }```
vestal arch
#

and would you ever use 2 different targets for those separate actions?

shadow wagon
#

like in the video, I need to reset the position when the mouse is down and released

vestal arch
#

why not have something like this

  [Serializable]
  public class CursorTarget
  {
    public Transform target;
    Vector2 Point;

    void MouseDown()
    {
      Point = target.position;
    }
  }
vestal arch
shadow wagon
#

that moving gizmo changes color depending when the mouse is held or not

#

mb that its not clear πŸ™

shadow wagon
# vestal arch why not have something like this ```cs [Serializable] public class CursorTar...
   public void Update(float dt)
   {
     MouseInput();

     void MouseInput()
     {
       if(Input.GetMouseButtonDown(0) && !Held)
       {
         MouseDown();
       }
       if(Input.GetMouseButton(0) && Held)
       {
         MouseHeld();
       }
       if(Input.GetMouseButtonUp(0) && Held)
       {
         MouseRelease();
       }
       
       CursorLock();
     }

     Point += (Vector2)Input.mousePositionDelta * dt;
   }```the target update method is like this, I know `MouseInput()` is a bit sloppy but I'll worry about it later
#

I was too lazy to dig through my files to find where I wrote that same thing in a much cleaner way

vestal arch
#

what's up with that update method

#

is this called from some actual component's update?

shadow wagon
#

Arm is a MB class

steady bobcat
#

man time to use the new input system

#

that looks trash

vestal arch
#

Time.deltaTime is still accessible in non-components, but also, mousePositionDelta is already per-frame, you don't need dt

shadow wagon
#

Input.mousePositionDelta is only temporary just as I only need to test this with a single mouse

steady bobcat
#

multiple mice i have no idea though

#

I presume you can make your own virtual pointers in unity with this but i have yet to use player input myself

shadow wagon
#

its just a custom mouse controller. offers mostly the same properties that the Input system does, just that I read it from a mouse class

#

Point += (Vector2)Input.mousePositionDelta * dt; becomes Point += _mouse.Delta * dt;

#

and later that MouseInput class will look something like this

  void UpdateGripState()
  {
    bool gripButton = _isLeft ? Mouse.Button2 : Mouse.Button1;

    if(gripButton && !_gripping)
    {
      HandleGripStart();
    }

    if(!gripButton && _gripping)
    {
      HandleGripEnd();
    }
  }```
steady bobcat
#

InputSystem does provide device access too and is probably the better option moving forward

#

and has events to better get the device data

shadow wagon
#

I'm not sure if it would have any way to understand how two mice work at the same time

#

plugging two mice in on windows, both control the cursor, but it switches focus on whatever mouse was moved most recently

vestal arch
#

wdym it switches focus?

#

don't both give their own pressed/released events

shadow wagon
#

if i move the right mouse, the cursor follows it and its like the other mouse becomes inactive. moving that mouse makes windows focus on that instead

#

its the same unity, just it switches focus each Update frame

vestal arch
#

what if you move both in opposite directions at approximately the same speed

#

when i do that on my device it basically takes the sum of the movements

#

and from what i remember, other devices do the same

shadow wagon
steady bobcat
#

trying to do it all via the old input system mouse pos seems kinda dumb though

#

True accuracy would ofc be using the os api to get the actual device data but hopefully the input system can cover this somewhat

vestal arch
#

it's just taking input from both mice simultaneously

shadow wagon
#

this reads directly from the mouse driver

steady bobcat
#

OH okay so this is all extra stuff not needed

shadow wagon
#

I only use the input from unity right now as its easier for testing on a single mouse

steady bobcat
#

well goodluck to ya

shadow wagon
#

(its honestly a miracle in the first place windows mouse driver accepts two mice being plugged in)

vestal arch
#

why wouldn't it

#

laptops exist

#

plugging in a mouse already creates 2 mice

shadow wagon
#

oooh yeah πŸ˜†

#

I meant if you plug two USB mice in

vestal arch
#

functionally the same thing as a trackpad + mouse

shadow wagon
#

it could have been designed to only allow input to be registered by the mouse that was plugged in most recently

#

because who is really going to ever plug two mice into a PC to use both together

vestal arch
#

also it would mean you can't passively have a dongle plugged in alongside a mouse on your desk

shadow wagon
#

I forgot trackpads exist haha

vestal arch
#

jokes aside, i think it wouldn't make sense that device drivers could only work one at a time for a given device type

#

having multiple printers available isn't unthinkable in even a basic computer setup

#

beyond that, multiple screens is very commonplace

#

and because laptops, multiple keyboards and mice are also common
plus bluetooth and dongle connections

#

so i think it definitely makes way more sense that device drivers in general allow multiple devices of the same type at the same time

#

-# not trying to argue, just thinking out loud, sorry if it comes off as that

shadow wagon
#

yeah, I hadnt thought of it like that

night harness
#

Then you also have controllers with weird mouse support sometimes

vestal arch
#

oh damn controllers is definitely a really good example of why multiple devices need to be supported

shadow wagon
#

theres something fun about using two usb mice to move two things around at the same time, and its surprisingly not that difficult to control like I had expected

night harness
#

Download a guys weird file from 2010 and get a wiimote in the mix πŸ˜„

shadow wagon
#

wiimote as a controller for a unity game could be fun

vestal arch
#

this discussion reminds me of tom scott's emoji keyboard lol
fun watch about relating to multiple devices if you haven't seen it

night harness
#

That one guy played overwatch as Pharah with a baguette. Ensure your input system is ready for that

vestal arch
#

baguette is a type of bread and bread is square so obviously that's a key hence a keyboard smh

shadow wagon
#

damn! they really got this using everything related to the wiimote

#

I cant see the speaker listed though 😦

shadow wagon
#

oh, its in the "future changes" limbo

#

maybe one day if I find my old wiimotes, I might try it out

halcyon steppe
#

Why am I getting this Error? I used this exact same command in a previous script without issue and I am stumped why it is not working

vestal arch
#

if you did the exact same thing then it probably did not work, or maybe sixteenthNotes was just empty so it never reached the part with issues

halcyon steppe
#

Am I not initializing the array on line 160?

somber nacelle
#

that initializes the array, but arrays are initialized with all of their elements at the default value for the type. which for classes is null

vestal arch
halcyon steppe
#

Right, i forgot to do that, thanks

viscid plaza
#

Why is my wheel collider doing... this?
The code is literally this:

private void MoveCar(float force = 0f)
{
    foreach (Wheel wheel in _wheels)
    {
        if (wheel.IsOnGround())
        {
            wheel.ApplyForceToWheel(force);
        }
    }
}

public void ApplyForceToWheel(float force)
{
     WheelCollider.motorTorque = force;
}
#

The car is currently lodged against an obstacle, but it starts heavily jittering when it drives. This didn't use to happen before, it randomly broke.

leaden ice
wintry crescent
#

I have a huge static class, that I only now realised must be an interface. Am I really lost, and I need to convert it to a non-static class?
For context, the class is an Eventbus, used across the whole game. I need a FakeEventBus for unit tests now...

viscid plaza
worldly stirrup
#
    {
        Debug.DrawRay(transform.position, -transform.up * groundBodyRayLength, Color.red);
        RaycastHit2D hit = Physics2D.Raycast(transform.position, -transform.up, groundBodyRayLength, level);
        if (hit.collider != null)
        {
            Vector2 averagePoint = Vector2.zero;
            foreach (Transform step in stepTargets)
            {
                averagePoint += (Vector2)step.position;
            }
            averagePoint = averagePoint / stepTargets.childCount;
            averagePoint.y = averagePoint.y + bodyYOffset;
            p = new Vector2(transform.position.x, averagePoint.y);
            transform.position = Vector2.MoveTowards(transform.position,p,delta*posSpeed);
            var targetRotation = Quaternion.LookRotation(Vector3.forward, hit.normal);
            transform.rotation = Quaternion.RotateTowards(transform.rotation, targetRotation, delta * rotationSpeed);
        }
    }``` Function that rotates the body
#
    {
        RaycastHit2D hit = Physics2D.Raycast(stepTarget.position, Vector2.down, pb.groundTargetRayLength, pb.level);
        if(hit.collider!=null){
            Vector2 point=hit.point;
            point.y+=pb.stepTargetYOffset;
            stepTarget.position=point;
        } 
    }``` Function that sets the step targets position to be on the ground
sonic bloom
#

Does anyone know how precise accelerometer data i can get, how many decimal places

#

I am currently using Input.acceleration

leaden ice
sonic bloom
#

yep, but i am only getting up to 3 decimal points

#

is there any documentaion , i couldnt fiund any

brave geyser
#

Is that not precise enough? For any input like that, I have normally had to smooth out the inputs to get anything useful anyway, so extra precision would essentially be eliminated.

hoary yoke
#

Hey! Is there any way to change 2d Sprites when pressing a key? ( for example a tilting "animation" when moving iykyk )

sonic bloom
#

and the noise is also really high

brave geyser
static oracle
#

Hello, I'm working with assetbundles and having an issue with static objects. My setup is each assetbundle contains one scene and each scene contains multiple gameobjects. I flag my gameobjects.isStatic = true then generate my assetbundle. But when I load it, nothing has the static flag - it's cleared?

hollow swan
#

Okay i really need some help, so i'm trying to do a system to switch between UI and do other simple action.

I have a class that is Serialized and hold every variable but not as MonoBehaviour so that in my main script can display it in the editor and also can instantiated as an array so i can do multiple action at the same time.

The problem come when i want to modify the editor so it doesn't show specific variable if some bool are not activated.

I'm using this code to get the target (i know it look empty it's just to give out an exemple)

[CustomEditor(typeof(UISettingsCompounents))]
public class UIEditor : Editor
{
    public override void OnInspectorGUI()
    {

        var uisc = (UISettingsCompounents)target;
    }
}

The problem is my target(class) doesn't have a any type like MonoBehviour or scriptable object, and i can't use one or else it won't show my class variables.

Is there any way to fix this?

leaden ice
#

WHy is it a problem that it's not a MonoBehaviour or ScriptableObject?

#

I don't understand your issue.

#

Oh wait sorry I get your problem

hollow swan
#
[System.Serializable]
public class UISettingsCompounents
{
    public GameObject uiWindow;
    public Scene sceneToLoad;
    public float loadDelay;
}
leaden ice
hollow swan
#

that my class that hold variables

leaden ice
#

not a custom editor

hollow swan
#

okay well thanks

leaden ice
#

check the code examples there

hollow swan
#

DUDE THANKS

#

It as been weeks seriously

#

i think i drank so much coffe i must have missed the option so many time

#

you are a life saver

iron crown
#

Been trying to implement multiscene workflow into my new project, and I'm struggling as it butts up against my existing workflow.

In my current workflow I create all UI at runtime, almost having exclusively empty scenes. So In a game like slay the spire or balatro, I try to create the flow: Start a run: Open the map scene, instantiate UI, pick an encounter, close map scene, spin up encounter scene, instantiate ui, close scene when it's over, enter a shop, do the same, etc. When not using multi scene workflow I typically have a sort of GameManager/GameMode class or FSM that manages the larger run in in one large scene, instantiating UI and closing at runtime as needed. With multiscene, the logic is separated into some permanently 'active' scene

My problem is, if I'm spinning up scenes additively at runtime, but keeping my logic scene the active scene, anytime I instantiate new objects they all get put in the active scene and at best I have to move them all to the scene they're supposed to be in, and at worst i'm switching active scenes away, instantiating, then switching back to my logic scene after instantiation is complete.

Feels like I'm struggling to make these two workflows work. Part of me thinks multi scene workflow just means "UI Scene, Gameplay Logic Scene, and Environment Scene". But I'm trying to make it properly multiscene by spinning up and down scenes as needed, but this whole 'active' scene instantiation thing is throwing me off. Any advice?

latent latch
#

Wouldn't just childing the objects under the specific scene node fix those problems?

#

Can also make like master scene nodes that act as the root to the scene to instantiate upon

iron crown
#

What do you mean by scene node in this case?

latent latch
#

Just a general gameobject that each scene incorporates that stays at Vector3.zero

night harness
#

instantiating objects and parenting under things so their not just in the scene root yeah

iron crown
#

Right I want to instantiate in different scenes at runtime, but I can't reference them at editor time because the scenes are empty at editor time. There's no gameobject for them to be parented under. Unless i'm misunderstanding

iron crown
#

Haha yeah I was doing that as a workaround, but I just hoped there was something better.

Do you folks who spin up scenes at runtime ever spin down your scenes?

#

Is that where the root of my problems are, wanting to spin up and down scenes regularly?

#

Like if you were playing any multiplayer game, spinning up a new scene everytime you entered a match or something. Then when it's over, spin it down

latent latch
#

I just treat scenes as a larger gameobject honestly

#

quicker to load and deload data, but that's about it

night harness
#

I can't concretely answer your question due to my experience but i'd wager it's likely a mix of you wanting to regularly spin up and down additive scenes + the fact you seem to prefer managing your scene's contents at runtime rather than in editor setup putting you someone against the common workflow Unity provides

#

Not that what your doing is wrong persay just maybe more niche

#

Though I might be mistaken but if your handling a majority of the games setup at runtime via instantiation I'm not sure which benefits of additive scene loading you'd actually be gaining?

latent latch
#

I usually just prefer a bulkier prefab workflow than really juggling scenes.

soft shard
#

I always wondered why scenes are mostly editor-only API where prefabs are both, I kind of prefer working in a similar workflow having multiple scenes managed at runtime instead of creating everything in the editor first (and then basically having to memorize the scenes build index instead of just referencing the scene as a object like you can with prefabs and the "new" input system)

night harness
#

I think it’s a bit of legacy stuff but also there’s aspects to how a scene being kinda static compared to a prefab giving it more options for baking certain information and memory related stuff

#

eg. all prefabs you have access to at runtime are loaded into memory where-as scenes are only in memory when they are loaded

#

I do personally use little scriptableobjects as a kinda wrapper for hardcoded scene names for the reasons you mention

latent latch
#

Scenes do in my opinion work better with assetbundles when you do want some constraints on what is loaded

soft shard
#

I can understand if theres some memory management with scenes, though I do think there should be a way to at least reference scenes or have a better organization system for the Build Settings window - using SOs as a wrapper sounds like an alright workaround for that (assuming the scene names dont change often)

latent latch
#

yeah scene reference entry point is a big pain, but I think batby did bring up some methods around that

#

Godot gives you that entry point, so you know exactly the first script to access when you do load those scenes

#

Otherwise you got to use Find, or have some subscription system the scene callbacks to when loaded so your gamemanager grabs

night harness
soft shard
#

Interesting, for one project (im still experimenting with so im not sure how reliable this approach is), im using a scriptable objects OnValidate to access the Build Settings editor API to try and get all the scenes and giving them a specific naming convention to store at runtime, so if I change a scene order or name, itll get updated after forcing the SO to "Validate", which also seems to happen before a build starts, though a lot of strange editor code to do it

night harness
#

Is there an ideal place to discuss suggested changes to the docs? Found a super niche solution to a problem i've been searching for for ages and it's seemingly completely undocumented

random stone
#

I am attempting to rig my character which is located in a different bundle onto, could this be done possible with a string path code? Not have any success with the following code.

0 SkeletonBone data
1 string m_Name = "Body"
1 string path = "sharedassets0.assets.resS"
1 string m_ParentName = "CC_Male_Rig(Clone)"

0 pair data
0 unsigned int first = 2073732236
1 string second = "Body"
1 string path = "sharedassets0.assets.resS"

cosmic rain
#

Other than that, maybe make a post on the forum

night harness
#

ah ok, sounds good

night harness
toxic quail
#

Hey guys not really sure if this is the place to ask this, but I'm having trouble initializing the camera using XR Origin. I'm creating the camera object and is has the movement controls which are working. The objects in my scene are appearing just not the camera feed. I'm sure I misconfigured a setting somewhere I'm just too new to know where. Thanks in advance gusy

toxic quail
#
``` I believe this is the issue
normal niche
#

Hello, i was wondering if there are any downsides to a method ive been playing around with compared to using just JSON for in game settings. This is the code i'm playing around with but maybe theres something bad with using a scriptable object here or just this approach in general? I havent seen it before so thats why im unsure, im just playing around with different ideas: ```[CreateAssetMenu(fileName = "GameSettings", menuName = "Game Data/Game Settings")]
public class GameSettings : ScriptableObject
{
public float masterVolume = 1.0f;
public int resolutionIndex = 0;
public bool isFullscreen = true;

public void Save()
{
    PlayerPrefs.SetFloat("Volume", masterVolume);
    PlayerPrefs.SetInt("Resolution", resolutionIndex);
    PlayerPrefs.SetInt("Fullscreen", isFullscreen ? 1 : 0);
    PlayerPrefs.Save();
}

public void Load()
{
    masterVolume = PlayerPrefs.GetFloat("Volume");
    resolutionIndex = PlayerPrefs.GetInt("Resolution");
    isFullscreen = PlayerPrefs.GetInt("Fullscreen") == 1;
}

}```

latent latch
#

More of a question of Json vs PlayerPrefs really

normal niche
#

it wouldnt look exactly like this obviously, its more of a template for how im thinking

#

okey, i see

#

but theres no immediate badness so to say about it?

latent latch
#

Assuming you're serializing them into other monos on the editor then it's preferred, otherwise a plain c# class would work fine too

normal niche
#

okey, that sounds good, this is just templating so far but that helps, thanks!

latent latch
#

nothing too special about SOs besides the fact you can move them around the editor

normal niche
#

yeah thats fair, i just want something quick up and running tbh, im probably going to switch to json when other more important systems are done. This was mostly me wanting to try some new features to learn new stuff 😁

#

thanks for the help!

lean sail
narrow sapphire
#

Things like stats for enemies etc.

#

That are consistent through all play sessions for everyone everywhere

#

You CAN serialise into jsons and stuff but like

#

If you are doing that… just use jsons

narrow sapphire
latent latch
#

It should save. The only large problem with player prefs is the values breaking when updating the game, but other than that this seems fine to me

lean sail
narrow sapphire
#

Oh sure in that case why use so at all tbh

modern epoch
#

Does anyone know the a star pathfinding project

austere vessel
#

I need help with a script in my project

night harness
#

ok

austere vessel
#

Could u help

somber nacelle
#

you should learn how to !ask a question πŸ‘‡

tawny elkBOT
normal niche
#

but yeah, i can see why its good to avoid, ill play around with it for fun but JSON seems like the simpler and better solution tbh. Good discussions tho, interesting points.

modern epoch
#

Can anyone help me with a star pathfinding

somber nacelle
#

Don't Ask To Ask
but also if it is with a specific asset you should probably seek that asset's support community

last quarry
grand aurora
somber nacelle
#

don't set the destination every frame, set it every X amount of time (where X is a high enough number that you aren't causing the agent to constantly recalculate its path but also low enough that it's not incredibly obvious that it isn't tracking the player each frame)

#

i usually go with every half second or so in my prototypes

grand aurora
somber nacelle
#

with no context i could not say why that didn't work

#

but that's also not a great way to handle it anyway. a simple timer in Update is sufficient

grand aurora
somber nacelle
#

well if you have confirmed it is the surface then wait for an answer in the ai navigation channel because it wouldn't be a code issue.

grand aurora
somber nacelle
#

what? how is that even remotely related to what i said? i said that since you have confirmed the issue is with the navmesh surface then you need to wait for a response in the #πŸ€–β”ƒai-navigation channel where you forwarded your question from. this is a code channel, if you have confirmed your issue isn't in the code then it does not belong here.

somber nacelle
dire crown
#

Is foreach still slow in unity?

leaden ice
dire crown
#

slow might be farfeched, but i mean slower than iterating with indices

leaden ice
#

Maybe you're thinking about some years in the past in the Mono runtime when some of the built in collections might have allocated GC but that was fixed like 10+ years ago

#

foreach may still be slower than a regular for loop but it's most likely not considerable enough of a difference to matter. Use the profiler if you are having a framerate issue.

dire crown
#

yeah, it's not a big issue. in this case it's taking 0.02ms. The reason im optimizing this is because it's part of recursive code that might have more than 2000 layers, so it adds up

late lion
#

Are you profiling in builds? IL2CPP will have different performance characteristics when it comes to this sort of overhead.

dire crown
#

true, i guess it's time to move back to builds

leaden ice
#

You can also just switch it to a regular for loop and see what difference it makes if any

#

If it's for edification

dire crown
leaden ice
steady bobcat
#

Oh god yea that may be too much

dire crown
#

Since it's a treelike structure it's hard to move it into an iterative process (if it's even possible) The way it's built I have the trunk of the tree and say, give me the data! and then it goes through the tree as many levels as needed until i get one single output result

leaden ice
#

it's always possible

dire crown
#

It's not so much about being possible, but more of the complexity and the cost that it introduces

night harness
#

i feel like if your profiling a foreach loop you might already be in those complex waters already πŸ˜›

dire crown
#

that's true hahahaha

leaden ice
#

It's probably not as complex as you think.

dire crown
#

Here's a quick drawing of a really really simple graph. Every block is a node and it's a graph editor, aka, they can be arranged in many ways. Special notes apart from the simple ones, the red is a branch, meaning left or right is evaluated depending of another branch (that i forgot to draw). The big square with many arrows is a dettached node that doesn't follow the branching but generates data as requests are done. And the square with squiggly line is a node that first gets data of a branch, calculates, and then gives that data to the first node of another branch to then calculate more data.

If i had to iterate over nodes i need to:

  • Go from left to right to get the order of all nodes, and so going through all depths
  • Go from right to left (somehow knowing exactly what is a starting node and what isn't) but then there are things that I can't do, like branches for later nodes
#

if I go first from left to right to get the order, and then start iterating it's possible, but the issue of going through all depths would still be there

vestal arch
#

what's the arrow relation here?

#

a dependancy?

#

what does each node represent?

leaden ice
#

You might not want to refactor, that's fine

#

I'm just pointing out that if you find limits with recursion, the option is there.

iron crown
#

Think a game like slay the spire, or any other roguelike deckbuilder where you have a run comprised of multiple smaller runs. Each run is comprised of unique encounters and unique bosses.

Please talk me out of trying to build a hierarchical state machine for this. Please tell me an enum based state manager is good enough, I don't even need the state pattern... Right?

steady moat
#

And you do not need it to be hierarchical same if it would make sense. However, using enum to represent each state is not a good idea even if you only use it as a way to switch between them.

low spear
#

I'd like to sort a number of gameobjects in the hierarchy by their world position (in this case Z), because they have UI elements. What's the best way to re-order gameobjects - detach them all from their parent and re-add them?

steady bobcat
#

SetSiblingIndex() on their transform

fiery steeple
#

Hey, is there a way to give a name to each enum entry that will be displayed on my UI in game without having those underscore or it being uppercase please ? And without creating a method that takes that enum, to PascalCase it, then remove the _ symbol.

I want to see first if there's something that does that directly without me coding all that stuff πŸ˜„

Like the same thing I did with the attribute [InspectorName("Task Name Here")] but I want for the stuff in game

vestal arch
fiery steeple
vestal arch
#

wdym "does it for you"?

#

what's your intended usage?

fiery steeple
#

like for instance in Unreal, there's an attribute called DisplayName(), so it does all that complex stuff behind the scenes for you

#

so I don't have to write my own method to do it

vestal arch
#

you want to.. extract the value specified in InspectorName..?

eager tundra
#

if this is user facing you probably shouldn't rely on that behavior anyway, especially if you intend to localize your game at some point

vestal arch
#

(though im pretty sure you don't actually need any of those InspectorNames)

fiery steeple
leaden ice
vestal arch
fiery steeple
#

Look how beautiful it looks right now

#

compared to before

leaden ice
fiery steeple
vestal arch
#

ohhh wait enums are usually in pascalcase already lmao

simple egret
#

If you want the value on your UI, then you can use a bit of Reflection to get the attribute and extract its string property

vestal arch
#

yours happens to be in macrocase so you had to specify your own names

leaden ice
fiery steeple
fiery steeple
iron crown
fiery steeple
vestal arch
fiery steeple
leaden ice
#

So it'd make sense to make some mapping code and use it in both places

fiery steeple
leaden ice
#

Rather than duplicating the mapping which can go out of sync

fiery steeple
vestal arch
#

huh

fiery steeple
vestal arch
#

-# my ide always screams at me for not following convention πŸ˜”

#

but yeah enums are typically PascalCase

#

if you do that you get the inspector names for free

leaden ice
fiery steeple
vestal arch
#

well clearly not lol, as seen in your "before" screenshot

#

but you wouldn't use _ in PascalCase

fiery steeple
vestal arch
#

it's called localization

fiery steeple
# vestal arch it's called localization

How does it work ? Like is it like in Unreal where Unreal grabs all the strings present in your game and give you that list and you can use the localization tool to translate each of them ?

vestal arch
fiery steeple
#

I'm scared to do a mess with it πŸ‘€

vestal arch
#

do you have vcs?

leaden ice
#

With lots of tools for different use cases

#

It's not simple enough to describe in one sentence

vestal arch
fiery steeple
leaden ice
#

Not visual studio

#

I.e. git

#

Or UVCS

fiery steeple
leaden ice
#

No

fiery steeple
leaden ice
#

You should practice and get better. It's an essential skill for making any kind of software product like a game

fiery steeple
#

I agree

steady moat
# iron crown It's funny you say enum based solutions aren't great, because it's like all over...

If you mean the following, then it is obviously bad whatever the rest of internet means.

public class Gameflow {
    public MyStateEnum currentState;
    public int XStateSpecificData;
    public int YStateSpecificData;
}

if you mean, then it can work depending on your use case. (I.E. you reuse the same state over and over again.)

public abstract class State {}

public class Gameflow {
    public Dictionary<MyStateEnum, State> states;
    public State currentState;
}
steady moat
#

However, in your case I would simply recreate my state each time and keep whatever logic that needs to be share elsewhere. By example, you might have a "Run" class that represent the current run. I believe it is better because you might want a run to outlive the actual "execution" of the run.

gleaming island
gleaming island
#

In my Unity terrain the FPS drops drastically when I add grass, in this case I am adding it as if they were trees with the tools

#

My grass is composed of 3 planes that render a texture of the grass and the shader is in charge of giving it a little movement

#

Now, as I said, the performance drops a lot and the draw calls increase a lot and I don't know how to instantiate the grass on the GPU because, as I said, there are 3 planes that make up the grass.

#

These Planes are children of an object that has nothing, so they are not a complete mesh

primal gale
#

how can I make AudioSource.PlayClipAtPoint work in 2D? the sound is all quiet

leaden ice
#

make sure you have an audio listener in the scene, close enough to the chosen position

#

and make sure you haven't disabled sound in the game view window

primal gale
#

but like my other sound from firing a bullet is normal while the playclipatpoint (using ti cuz I have a gameobject destroy for the bullet) makes it all quiet

#

like its there

#

just barely audible

leaden ice
#

or it's a quieter clip

primal gale
#

Ive tried it with the same exact clip and setting the location to my players rigidbody

leaden ice
#

You'll have to start showing code/screenshots/videos

#

also the inspector of the audio source you're comparing with would be nice to see

primal gale
#

its on my bullet script which usually would break the bullet on trigger which it does

#

but I heard that because im trying to destroy the object a normal audio.Play() wouldnt work so this was my solution though its quiet

leaden ice
primal gale
#

then the OG clip which just plays upon firing

leaden ice
#

also what are you passing in for volume

primal gale
#

it was just a float

#

experimenting if it could go above 1f

#

it did not

leaden ice
leaden ice
primal gale
#

ive heard that this problem might have to do with the spatial settings of PlayClipAtPoint being set to 1 which is usually 3d

#

though not sure if that is the problem and if it is how to set it to 0 (2D)

leaden ice
#

Yeah that could be it for sure

#

I would say one option is to just play it at the z position of your audio listener

#

i.e.

Vector3 position = transform.position;
position.z = mainCam.transform.position.z;
AudioSource.PlayClipAtPoint(clip, position, volume);```
primal gale
#

Okay! Worked wonders thanks. Last issue with this is that the sound does now change based on distance which ig I can work with, is there a way to make that universal?

#

I know that is literally the entire point of this method

#

but it works with destroy so

leaden ice
#

instead of the position of the object that's exploding

#

PlayClipAtPoint(mainCam.position, ...)

primal gale
#

oh wait hold on got it to work

#

thanks for all the help!

vague spoke
#

Yo yo just generally asking how do you guys save game data in unity? do you just generally use player prefs for everything?

night harness
#

The opposite

lean sail
vague spoke
latent latch
#

json's a pretty cool guy

glacial moss
#

yeah I love JSON

pastel patio
#

Hey guys, how would you write code for the following kind of structure? Or if someone has a recommendation for a better structure in the first place-

class CreatureStatemachine;

abstract class CreatureState;

class PlayerStatemachine : CreatureStatemachine
{
  public StunState stunState;
  public ProneState proneState;

  [Serializeable]
  public class StunState : CreatureState
  {
    // Requires access to the creature and the statemachine
  }

  [Serializeable]
  public class ProneState : CreatureState
  {
    // Requires access to the creature and the statemachine
  }
}
#

Should I just expose a field to manually assign the creature in each state?

#

Or would it be a good idea to assign those things in the constructor as the field gets initialized? Nvm forgot that previously I tried this, but this cannot be passed during field initialization.

chilly charm
#

Could you do something like this? You can pass "this" in as a parameter to a constructor. I wouldn't want to set this up in the inspector

pastel patio
#

I could however take a very similar approach and only initialize the necessary fields via a function or so

#

Yeah, it's decided then, thanks!

chilly charm
#

Yeah I think you are right, if you don't have a constructor then I would just add an initializer function to each state and make that part of the abstract class.

fiery steeple
#

is there a built in Unity system to turn a string into a camelCase or PascalCase format ?

dusk apex
fiery steeple
#

so not in the Inspector / Unity Editor

dusk apex
# fiery steeple so not in the Inspector / Unity Editor

You'll need to ask a Visual Studio support server. Highly doubt it, natively, but perhaps there may be tools or whatnot to accomplish what you're needing to do. The Visual Studio Editor and it's environment is unrelated to Unity (other than allowing you to create scripts with Intellisense etc)

fiery steeple
dusk apex
fiery steeple
dusk apex
eager tundra
#

this type of thing is very simple to implement, if you couldn't find any builtin utility methods with a quick search, then you should just implement yourself

#

especially true if you already know the original format that you want to convert to any other case

fiery steeple
dusk apex
fiery steeple
dusk apex
#

Lookup the ms docs for the string class or ask !csds

tawny elkBOT
fiery steeple
#

to put it simply πŸ™‚

somber nacelle
jolly phoenix
#

hello. i'm attempting to open an older project and i can't find the jobs package in the package manager. was it remove or changed?

tiny delta
#

Howdy folks. My game has a few spells the players can cast. These have their behavior determined by a scriptable object, which has an array of a "Module" class which has info on one type of property the spell has.

Would it be best to replace the "Module" class with scriptable objects that have the same info? Or is there some other way to organize this better? I want to work on my separation of concerns and such.

primal gale
#

how can I call my players x movement direction wtihout ti changing?

Using a knockback function which deals knockback based on the Input.GetAxisRaw("Horizontal") but lets say I move left and hit my enemy (which is to the left of me) the enemy will be knocked back towards me since im moving left

#

How can I get it to just deal knockback in the opposite direction of where I am in relation to the enemy

#

and when im standing still the knockback will just go straight up

#

this is the function call

naive swallow
#

Seems like you've got variables to handle that, hitDirection and constantForceDirection. You probably want to change those based on where the player is relative to the enemy rather than what direction they're facing. Where do you calculate those?

primal gale
#

its meant to still deal knockback even when the character isnt moving at all

#

just not sure if the Input.GetAxisRaw("Horizontal") will do the job for the inputDirection variable because it deosnt seem to be relative

#

I do have a rotating object that rotates around the player where bullets are fired, should I call that transform instead?

naive swallow
#

Instead of basing the direction on input, base it on whether the attacker is on the left or the right of this object

primal gale
#

aight ill give it a try

fiery steeple
#

I'm trying to follow this tutorial https://youtu.be/fHPaG5C6P1M to do the localized text thing that uses a variable that changes depending on some code (in his example the variable is called holeNumber and he has the entry on runtimeUI.level which is a single entry but in my case I have multiple routines per day that switches depending on the time of day).

Each daily routine has a specific starting time and ending time. And in my Localization Table, each of these routines have their own key, compared to the tutorial guy he has only 1 key (Entry Name). So I'm kinda confused on how to make it work πŸ€”

Here's my method that's called everytime the daily routine changes but it doesn't work. For some hours it shows nothing (I guess empty string), and other days it tells me No translation found for 'New Entry' in DailyRoutines which is because I don't know what to name the key as I have multiple of them that I need to use on my UI depending on the current routine 😬 please

agile quail
#

does anyone know why im getting this error message? InvalidOperationException: You are trying to read Input using the UnityEngine.Input class, but you have switched active Input handling to Input System package in Player Settings.
UnityEngine.Input.GetKey

#

the message says its coming from this here but it might be a unity setting problem maybe

vestal arch
young yacht
#
IEnumerator CalculateKnockback(int knockback, GameObject gameObject)
    {
        Rigidbody enemyRb = gameObject.GetComponent<Rigidbody>();
        NavMeshAgent agent = gameObject.GetComponent<NavMeshAgent>();

        agent.enabled = false;

        Vector3 direction = gameObject.transform.position - playerController.gameObject.transform.position;
        enemyRb.AddForce(direction * knockback, ForceMode.Impulse);

        yield return new WaitForSeconds(0.2f);

        enemyRb.angularVelocity = Vector3.zero;

        agent.enabled = true;
    }

could anyone help here? im trying to make the gameObject stop after AddForce to it

#

i disable the NavMeshAgent, add force then enable it again but the enemy is just sliding through the map

leaden ice
#

I think you meant to do linearVelocity

young yacht
#

maybe i can add drag?

leaden ice
young yacht
# leaden ice well it's going to continue until .2 seconds are up
IEnumerator CalculateKnockback(int knockback, GameObject gameObject)
    {
        Rigidbody enemyRb = gameObject.GetComponent<Rigidbody>();
        NavMeshAgent agent = gameObject.GetComponent<NavMeshAgent>();

        agent.enabled = false;

        enemyRb.linearVelocity = Vector3.zero;
        enemyRb.angularVelocity = Vector3.zero;

        Vector3 direction = gameObject.transform.position - playerController.gameObject.transform.position;
        enemyRb.AddForce(direction * knockback, ForceMode.Impulse);

        yield return new WaitForSeconds(0.1f);
        
        enemyRb.linearVelocity = Vector3.zero;
        enemyRb.angularVelocity = Vector3.zero;

        agent.enabled = true;
    }

tried setting to .1f but dude is still sliding like there's no tomorrow

leaden ice
#

Are you destroying the projectile immediately on the collison?

#

That would make the coroutine stop running before the end part can run

young yacht
#

ah actually you might be onto something

#

i think thats it

leaden ice
#

yeah try running the coroutine on a different object that doesn't get destroyed.

#

The video really helped it click for me that this is being started by a projectile that's getting destroyed

vestal arch
#

could have the one being hit do the knockback on itself

young yacht
#

because i got like 20 types of different bullets

#

this bullet is the only one doing knockback effect

young yacht
#

working now

#

thanks!

primal gale
#

Trying some gun recoil/knockback to my 2d side scrolling player, I want my cube to be forced back after firing the gun (which rotates about the character)

#

it currently works but its like jerky

#

when i fire in a direction the player moves like 2 inches to the left

#

almost teleports

#

is there something other than AddForce I can use?

vestal arch
primal gale
#

I get the ForceMode2D.Impulse

#

should I still use addfroce

leaden ice
leaden ice
primal gale
leaden ice
#

You would need to disable that code for the knockback period

leaden ice
#

it would get to 0.35f, and you'd do a knockback and reduce it to 0.05f

primal gale
leaden ice
#

yes

primal gale
#

so how would I counteract that

leaden ice
#

disable that code during the knockback

primal gale
#

just like call if !ApplyKnockback over the movement code

leaden ice
#

or switch to controlling everything with additive forces instead of overwriting velocity

leaden ice
#

you would need to have the knockback last a certain amount of time or something

primal gale
#

also adding ForceMode2D.Impulse fixes the stuttering, but now it only moves up and down rather than in any direction

vestal arch
leaden ice
primal gale
#

oh right

#

yeah ig ot this for my jump

leaden ice
#

no it's not this code that's causing it

#

it's your normal movement code

primal gale
#

wait how come I cant call my knockback script

#

its public

#

this is in my movement script

leaden ice
#

or if you look in your unity console

primal gale
#

just says it isnt recognized

leaden ice
#

Then you don't have any class by that name

primal gale
#

also how come my code isnt green

leaden ice
primal gale
#

like the monobehaviour and whatnot

leaden ice
#

!ide

tawny elkBOT
primal gale
#

but my other scripts work perfectly fine

leaden ice
#

did you put this script somewhere weird

primal gale
#

hold up it might be not updated correctly

#

the GunKnockback script shows up as this

#

while my other ones are Assembly-CSharp

#

ill try to update yet again yay

eager tundra
#

is the file extension correct?

leaden ice
#

Good question and also is it in the Assets folder?

#

or is it somewhere weird

#

e.g. did you put it inside some package folder or something

primal gale
#

no

#

its literally the same place I have eveyrthing else

#

not sure why it says miscellaneous its in the right place

#

when I try to create new scripts it says the same thing

leaden ice
#

do you have a compile error in the console?

primal gale
#

nope

#

the External Script Editor is on visual studio too

leaden ice
#

Can you show some less cropped screenshots

#

not cropped at all would be ideal -e.g. with the project window visible in VS

primal gale
#

no problem

#

then heres an actually working script

#

script editor is also updated I hope

#

trying to find my visual studio files rn

leaden ice
#

Ah your VS project window is hidden

primal gale
#

wdym

leaden ice
#

or sorry

#

the Solution Explorer window

primal gale
#

yeah I was looking for that

leaden ice
primal gale
#

aight I got it

#

the GunKnockback script is under Assets like all my other scripts

#

I really should organize them but rn they are all in the same Assets folder

#

oh hold on

#

GunKnockback does not show up as a C# script

#

like its there as a file

#

but not as an openable script

eager tundra
#

did you modify the .csproj file manually somehow?
might be a good idea to run the "Regenerate Project Files" under Preferences -> External Tools

leaden ice
#

i think you might be able to fix this with:
Edit -> Preferences -> External Tools -> Click "Regenerate Project Files"

#

damn, jinx

primal gale
#

gonna try and duplicate a file that works directly from VS code to see if itll function

#

is this important at all?

#

the No supported VCS diff tools thing

#

Okay I somehow managed to fix things

#

not sure how or why but thanks fellas

#

okay now back to the actual reason why I am here

leaden ice
#

so after that's fixed is there still an error?

#

My guess was VS was just showing an error because the csproj was messed up and it didn't know about that file.

#

Unity was probably fine with the compilation

primal gale
#

honestly no clue why it messed up int he first place

#

there were no issues with the GunKnockback code or anything

#

anyways, trying to do this with a bool taht checks if im beingj knocked back or not

#

in the player movement

leaden ice
#

alright - seems reasonable enough. What's the issue?

primal gale
#

nope, stll only works up and down

#

ill try to print a debug in the movement script

leaden ice
#

you're setting isBeingKnockedBack = false every frame

primal gale
#

oh wait thats in the update

leaden ice
#

you would need a coroutine or something here

#

to set it to false after some amount of time

primal gale
#

ah damn

#

I hate coroutines

leaden ice
#

or you could use a float timer

#
float timeOfLastKnockback;
float knockbackDuration = 0.5f;

public bool IsBeingKnockedback => (Time.time - timeOfLastKnockback) < knockbackDuration;```
#

and do timeOfLastKnockback = Time.time; when you do the knockback

#

for example

#

(quick and dirty example)

primal gale
#

like so?

#

oh wait I tihnk that may have worked

#

hm no

#

almnost there, but the character slides for the duration of knockbackDuration which I mean makes sense

leaden ice
#

yes that's correct

primal gale
#

but it doesnt feel very smooth

#

ill try messing wtih the duration

leaden ice
#

So you could fix this in a few ways - one is rather than completely locking out the player controls, you do it gradually

#

two you can change the duration

primal gale
#

definitely feels better when I make the duration shorter, although I still don't like being locked out of all controls

#

actually it aint too bad setting it to 0.1f

#

oh eyah thats perfect

#

thank you for your help

#

and for dealing with me lol

steady bobcat
#

wait you use it later wtf

primal gale
#

gottem

rigid island
#

blindly copying it they don't realize its the same reference they could've used mainCam.ScreenTo

steady bobcat
#

The update/start comments are still there so clearly a beginner πŸ˜†

primal gale
#

hey if it works it works

steady bobcat
#

we dont do that here

#

as a beginner its fine but later when you want to do things in a faster and more reliable way you will learn to abandon finding by tag/name.

primal gale
#

just copied it from my other script which controls the mouse rotation gun

steady bobcat
#

From the screenshot it appears mainCam isnt used so yea it can go. Using Camera.main is best to get the main camera or using a Serialized field for other cameras.

primal gale
#

is there any way to change the pitch of a PlayClipAtPoint method?

#

using it with my OnTrigger cuz I dont feel like using a coroutine and it seemed convenient

leaden ice
#

no

#

PlayAtClip is pretty limited

#

what you could/should probably do instead of this is just put one audio source on your camera and have it play everything with PlayOneShot

primal gale
leaden ice
#

you could make it a singleton

primal gale
#

I probably will just try a coroutine

primal gale
#

No so I attach the listener and stuff to the camera but it’s triggered by the OnTrigger on the bullet hit script

leaden ice
#

so? It's the camera now playing the sound

#

not the bullet

#

I said to put the audio source on the camera as well

primal gale
#

But how would I make the camera play the sound when I need to call the sound to play when the bullet hits

#

Just reference the mainCam?

leaden ice
#

Like I said, make the script a singleton

primal gale
#

I’ll try to

leaden ice
#

to make it easy

primal gale
#

I do not know what a singleton is

#

I am but a simpleton

leaden ice
#

the bullet script just has to do like AudioManager.Instance.PlaySound(bulletHitClip);

leaden ice
floral drum
#

so when using relay for multiplayer, im having an issue where my a script running on my client is saying that IsOwner = false, and i was under the impression that if it was a script attached to their character, they were always owner.

leaden ice
#

but if you're doing server-authoritative, I believe the server owns all NetworkObjects

floral drum
#

Well im doing a host to client connection so im not sure what that would be considered, pretty sure the host is considered the server right?

leaden ice
# floral drum Well im doing a host to client connection so im not sure what that would be cons...

Network topology is either distributed or client-server:
https://docs-multiplayer.unity3d.com/netcode/current/terms-concepts/network-topologies/

In a client-server topology, the server owns all NetworkObjects:

By default, Netcode for GameObjects assumes a client-server topology, in which the server owns all NetworkObjects (with some exceptions) and has ultimate authority over spawning and despawning.
https://docs-multiplayer.unity3d.com/netcode/current/basics/ownership/

floral drum
hollow plume
#

Hi. I have a question regarding making npcs. Usually we use nav mesh agent. However, this comes with some issues. Firstly, the nav mesh agent default behavior is moving towards the goal direction and slowly turn until it reaches the right direction, therefore causing a "sliding" effect. What I want is the character to move in a more realistic way, only moving forward while turning to march the next waypoint. Ive gotten this to somehow work by merging a character controller and a nav mesh agent and disabling the agents movement and handling everything myself. This works ok on flat surfaces but on terrain or different heights it becomes buggy and desynced and stuff. Do u guys have an idea on how the proper way it's done?

floral drum
#

agent.angularSpeed

#

makes him turn faster

hollow plume
#

That's not the solution.

#

What if I also wanna use root motion animation for movement

floral drum
#

gotcha, my bad i misunderstood what u were asking

hollow plume
#

No worries.

latent latch
#

I'd probably just check each update if they are looking at the direction, otherwise pause them from moving and correct the rotation

oblique spoke
hollow plume
hollow plume
#

Until they face the proper direction

latent latch
#

I think I've managed to do something with rigidbodies with agents to get that angular drifting and dampening in a project, but I mostly just use a* project now and its custom controllers have quite a bit more features than what unity provides

hollow plume
#

I've never used a*.

#

Is it an algorithm I write?

latent latch
#

a* is the algorithm, but a* project is a popular pathfinding library for unity

#

it's paid but has some features available for free

#

I would try the rigidbody idea though as I'm pretty sure you can manage something with that

oblique spoke
signal cape
#

hello, i need help with collision for my balls in a block breaker game, when my balls go very fast there is an issue with the balls (look at the video)

how i handle the collision :

private void OnCollisionEnter2D(Collision2D collision)
{
    if (collision.transform.tag == "block")
    {
        Damage_block(collision.transform.GetComponent<block_sc>(), collision.GetContact(0).point);
    }
    else if (collision.transform.tag == "ground" && death_refusal <= 0)
    {
        Destroy_ball();
    }
    else if(collision.transform.tag == "ground" && death_refusal > 0)
    {
        death_refusal -= 1;
    }
    transform.up = Vector2.Reflect(transform.up, collision.GetContact(0).normal);
}
private void OnCollisionStay2D(Collision2D collision)
{
    transform.up = Vector2.Reflect(transform.up, collision.GetContact(0).normal);
}
leaden ice
vestal arch
fiery steeple
eager tundra
# fiery steeple I'm trying to follow this tutorial <https://youtu.be/fHPaG5C6P1M> to do the loca...

there's a lot going on here
first, it's not showing anything because of either the result for GetBinding is null, or it's not convertible to LocalizedString
the first step would be breaking that line into two and figuring out what is going on β€” add some more logs there

second, what do you mean you don't know what to name the keys? you can name them whatever you want as long as it makes sense to you and you're able to reference that later somehow

fiery steeple
# eager tundra there's a lot going on here first, it's not showing anything because of either t...

By that I mean as the tutorial shows an example with the main menu buttons text, each of those text have a unique key which is logical. In my case I don't have a unique key for my text as that text need to change everytime a new routine starts so I have to give it a new key each time (from those existing in the table).

I cameup with this solution and it works but it doesn't update the text to the new change of language until it updates the text on the next daily routine and as it's a string and not a LocalizedString, I can't subscribe to the StringChanged event that happens when the user changes the language (mid game for instance)

sand zealot
#

hi! i need help fixing this issue, ive looked everywhere and have no clue what has went wrong

fiery steeple
sand zealot
#

oh really?

vestal arch
tawny elkBOT
fiery steeple
#

it makes it think that brace line 39 is to close the whole class making your method IsGrounded() outside of the class

#

that's why it complains

vestal arch
#

and your ide would tell you this if you configure it

sand zealot
#

ohhh

#

makes sense

#

thank you so much

#

something so little caused so much errors xD

eager tundra
fiery steeple
eager tundra
# fiery steeple I need the text to update in 2 cases : - When the player changes the game's lang...

right, but what's your current issue then?
you need a function for updating the text, then this function should be called on both occasions: when the routine changes and when the language changes
I guess you already can detect when a routine changes, so that should be done already
to detect when the language changes you probably need to subscribe to an event in LocalizationSettings (I haven't used the package, so can't give you much more details there)

fiery steeple
fiery steeple
shadow cradle
#

how can i have a hook attribute for vars?

leaden ice
shadow cradle
leaden ice
#

Use a property and an event:

public event Action<float> OnHealthChanged;

private float _health;
public float Health {
  get => _health;
  set {
    _health = value;
    OnHealthChanged?.Invoke(value)l
  }
}```
shadow cradle
leaden ice
#

Which is a good idea to enforce

steady bobcat
#

Also means only the owning class can =, elsewhere its only += and -=

shadow cradle
#

cool thnx guys

leaden ice
#

Basically makes it act like a publisher/subscriber model instead of just a regular delegate

fiery steeple
#

Hey, I have something wrong with my logic making the text on my UI (and I guess the CurrentRoutine variable too) doesn't understand that from 23PM to 6AM, the routine should be Lights Out while in my case it stays at Night Roll Call up to 6 AM.

leaden ice
#

it's checking if the current time is less than 06:00

#

when it's actually 23 hours or 1 day, and some minutes

fiery steeple
#

so I shouldn't use TimeSpan for the comparison ?

leaden ice
#

I didn't say that

#

I just said you're not accounting for the day boundary

fiery steeple
#

mhhh, so what's the solution ? πŸ€”

leaden ice
#

maybe something like, if the endtime is less than the start time, add 24 hours to it

#

at least in the second half of the day

#

if you're in the first half of the day, subtract 24 hours from the start time if it's after the end time

#

somethign like that

fiery steeple
leaden ice
#

I'm aware of what properties it has

#

if the current time is 23 hours

#

and you have a routine that goes from 22 hours to 6 hours

#

23 is not less than 6

#

but if you add 24 to it - so it's treated as 30

#

then 23 IS less then 30

#

23 IS between 22 and 30

#

so it will work

#

and, as I mentioned if it's 02:00

#

that's the first half of the day

#

so your routine that goes from 22 hours to 6 hours will be adjusted to -2 hours to 6 hours

#

and 02:00 IS between -2 and 6

#

So i think my logic will work just fine

#

so like:

TimeSpan startTime = task.StartTime;
TimeSpan endTIme = task.EndTime;
// Check if the task wraps around midnight
if (startTime > endTime) {
  if (time.Hours < 12) {
     startTime -= TimeSpan.FromHours(24);
  }
  else {
     endTime += TimeSpan.FromHours(24);
  }
}

// Then you do your normal logic here, using startTime and endTime isntead of task.StartTime/task.EndTime
fiery steeple
#

But doesn't your solution seem like a glitch in the matrix ?

leaden ice
#

I have no idea what that means lol

fiery steeple
#

Like it seems more like a patch on a wound than a real solution πŸ˜„

leaden ice
#

I disagree.

The real solution would be for your timestamps to all track which day they're on as well as just the time of day

#

but you don't want to do that, and you'd have to write a ton of really complicateed code to generate those timestamps from the local times all the time

#

another point would be that your timestamp should probably say 30:00 instead of 06:00 to really indicate it's meant to be on the next day

fiery steeple
narrow sapphire
#

bit more messy but seems easiest would be to just have 24 hours and for each hour you select the task

fiery steeple
night harness
#

Not a solution but just a question/thought when reading this as I haven't implemented something like this before. In some situations would it be maybe reasonable just to treat any time of day scoped task/code in a 3 day/72 hour context all the time instead of mostly 24 but sometimes more than that (72 because all of yesterday, all of day, all of tomorrow). and then you could restrict or display that info conditionally based on if it overlaps or not?

leaden ice
#

you just wrote 06:00

#

so you're treating it as a "time of day"

#

rather than an absolute calendar time

narrow sapphire
# fiery steeple

when you put end time 06:00 on the last task it doesnt magically know u mean the next day

#

yes it has the capability for that but...

#

doesn't mean whack if you don't tell it such

fiery steeple
#

so yeah I think the 24 hours solution you gave is THE solution πŸ˜„

narrow sapphire
#

can't you just put it ends on 24:00, then at the start of the day put lights out from 00:00 until 6

#

and just skip changing stuff if the next task is the same as current task

fiery steeple
narrow sapphire
#

don't see what's unclean about that

#

this also means you can switch routines

#

with your current how tf do u handle changing routines

leaden ice
narrow sapphire
#

if for example u wanted to like put the dude in solitary or something

#

or different routines for different days would be easier

#

instead of handling some edge case where people need to get up sooner or later but the lights out is hard set as until 6 am from the previous day

fiery steeple
narrow sapphire
#

well i mean its not especially hard but if you did it that way instead you wouldn't need any special logic at all

#

actually to be honest why do you need an end time at all?

#

why not just have start times only for everything

#

you can infer the end time by looking at the start time of the next task

leaden ice
#

it may be they're entering a zone at a given time and at any given time that zone may have a certain event happening or no event at all

#

so the question, when entering the zone, is "what is the current task happening now"

#

That's my understanding

fiery steeple
leaden ice
#

you could do it with putting free times in yeah

fiery steeple
#

yeah that's already the case now

fiery steeple
steady bobcat
#

Crossing a day boundary, you should be able to detect that or define it so both 22:00-23:59 and 00:00-06:00 can be true.

steady bobcat
#

If we get the total length of the event and then do start + duration, we can see if it goes past the day end (in whatever units you use).
Then you can perhaps change the end time used to be day end?

fiery steeple
steady bobcat
#

I don't really understand your current way of checking the event but using the lowest unit like seconds or milli seconds is easier.

fiery steeple
steady bobcat
#

If you track the day the player is in since starting the whole game then just work with time relative to that

#

All time can be second or ms since then and you can get the start and end time for events from that and work with this easier

fiery steeple
#

And I think at some point I wll need to pause the routine system for a minigame break (around like 6 PM) but I'm still thinking about that

steady bobcat
#

I mean your gameplay time and days not real time

#

If you pause that advancing when paused then you track it somewhere yes?

fiery steeple