#archived-code-general

1 messages ยท Page 159 of 1

leaden ice
#

^

#

let's say your movement input is (1, 1) for the current frame.
_sc.PlayerRB.MovePosition(new Vector3(move.x, 0, move.y));
is now going to move your object to the world space coordinate (1, 1)

#

you need to add the input to the position of the object to get a new position

swift falcon
#

๐Ÿ‘ What about the use of "AddForce," with a ForceMode of acceleration? That was also not doing anything to the movement of the character.

#

Also, something that I noticed is that the position is increasing exponentially in the inspector as soon as the player hits the ground.

vagrant blade
#

That's just a very small number that is essentially zero

#

Since nothing in 3D space is actually a whole number unless explicitly set.

leaden ice
#

also yeah that's a position of 0 basically

swift falcon
#

alrighty... would you reccomend attempting to continue with the use of MovePosition(), or should I look into other methods?

leaden ice
#

having no idea of what kind of motion / control feel you are trying to achieve with your game I have no comment

swift falcon
#

no worries! thanks for the info you were able to provide!

pure cliff
spring creek
pure cliff
#

int[a,b] is a square if a == b, but a doesnt have to be same as b and thus, rectangle :3

spring creek
#

That makes a lot of sense

tender vault
#

why is it that object.setactive(!object.activeInHeirarchy) works to set an object as inactive but object.setactive(false) doesn't? I thought activeInHeirarchy was a bool

leaden ice
#

and it is a bool

tender vault
#

Oh it DOES work fine

#

how would one go about making the object active once again

#

(true) doesn't work

leaden ice
tender vault
#

hrmm

leaden ice
#

it does

leaden ice
#

e.g. in Update

#

It won't.

tender vault
#

So if the game object is defined in the code of the object that deactivates it

#

I can't turn that object back on

leaden ice
#

But if your code is not running, it won't do anything

#

because it's not... running

tender vault
#

damn

#

I swear I had it set up so the boxer object could turn the hitbox object off and on

#
    void Update()
    {

    if (Input.GetKeyDown(KeyCode.X))
        {
        hitbox.SetActive(false);
        Debug.Log("Inactive");
        }

    if (Input.GetKeyDown(KeyCode.Z))
        {
       hitbox.SetActive(true);
      Debug.Log("Active");
      }  ```
#

uh oh I forgot to format again

wide dock
#

if hitbox is on the same object as your script then your script won't be active anymore too, thus update won't work

scarlet rover
#

edit it and add another ```

tender vault
#

Can I define public GameObject hitbox; to another object then?

tawny elkBOT
#
Posting code

๐Ÿ“ƒ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

๐Ÿ“ƒ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

leaden ice
scarlet rover
#

How do you get hatebin to give you a unique URL? I pasted the code then hit the disk to save thinking that should generate a URL but it did not

wide dock
tender vault
#

wait that's weird, none of the scripts for deactivating/activating object hitbox are in the object hitbox

leaden ice
#

try a diff one

tender vault
#

its all in boxer and it still doesnt run the update after

scarlet rover
leaden ice
#

unclear what the point of it is though ๐Ÿค”

scarlet rover
#

I have a parameter that is getting passed to the animator...if it is 0 it plays one animation, 1 it plays the other...I tried explaining it in the comment above that line in the code

wide dock
tender vault
#

are you telling me the order of the objects matters aswell?

wide dock
#

I mean the object where the script is

tender vault
#

OHHH

#

ah i got it

wide dock
#

And the object you're trying to deactivate

tender vault
#

boxer is the script for hitbox

#

thus when object hitbox is inactive it no longer updates

#

i need a new object

scarlet rover
strange jacinth
#

Hey, I have method that does component adding/removing in editor on GameObject hierarchy on every component of some type. How can i record undo in this method as single operation? It's curerntly running in Update loop with ExecuteInEditMode.

tender vault
#

@wide dock @leaden ice thank you guys for getting me back onto my old engine, works great

strange jacinth
leaden ice
strange jacinth
#

Ok, i'll try first one

scarlet rover
#

could you use that to do a rewind feature like the do in Viewport?

leaden ice
#

no

#

it's for the editor only

pure cliff
# scarlet rover Just looking for a code review when someone is free...Want constructive feedback...
  1. I prefer setting my components in Reset(), as it automatically handles self assigning and I dont need to drag and drop, means you wont be doing this work during runtime and adding longer load time to the game. Can also just manually drag and drop it

  2. Same thing Praetor said, you dont need the if/else, you can just do .SetInteger("Random", x)

  3. RandomAnimation = this.GetComponent<Animator>(), naming convention wise this is an Animator not an Animation, Unity has both things called Animations and Animators, its typically good practice to name your references to unity objects as NameType, so I would name this RandomAnimator, not ...Animation

  4. if (waitCompleted), I try and declare my class fields directly above the first method (vertically in the code) that uses them. In your example here I would have declared waitCompleted directly above Update. At first glance in this line I see you referencing waitCompleted but I have to scroll up half a page to actually see what it even is

  5. audioSource.Play(); you probably want PlayOneShot here for "SFX" style sounds, as PlayOneShot lets you overlap sounds.

  6. You use waitCompleted to trigger self destruction, but you could replace all lines of code that are waitCompleted = true; with straight up directly calling Destroy(gameObject);, also, you already destroyed the object in your "true" part of your if condition inside of WaitCounter.

#

Time.timeScale = 0; should this be 1f btw? 0 would freeze time or am I mistaken?

scarlet rover
#

it shows the UI window so I want everything to freeze

#

has a "you win!" screen

pure cliff
#

I see, Id be careful because IIRC thatll also "freeze" any UI animations you may wanna use... maybe?

scarlet rover
#

it would, I read that...I dont have any animations on it right now, but that makes sense... Can you paste a code snippet of what you mean here:

You use waitCompleted to trigger self destruction, but you could replace all lines of code that are waitCompleted = true; with straight up directly calling Destroy(gameObject);, also, you already destroyed the object in your "true" part of your if condition inside of WaitCounter.
pure cliff
#

so you can just remove waitCompleted and directly call Destroy instead

scarlet rover
#

I have it in the update...I was having an issue where the object was destroying before Time.timeScale was set back to 1

pure cliff
strange jacinth
scarlet rover
#

Thanks...only been working with C# for a week so really fresh sitll

#

I thought I did that before but obviously it was something different because that worked

pure cliff
#

your first half of the statement (the true part) is calling destroy before the other values are set I think

rain minnow
jovial vale
#

is there any good modern implementation of Thrift for Unity? Latest version which does seem to generate Unity-friendly code without issues out of the box is 0.9.2 via csharp generation, which is quite ancient and doesn't support any modern features like async support

leaden ice
#

You have a duplicate script in your project

rose dragon
leaden ice
#

You have another one

rose dragon
#

you're right

#

must of duped it twice

daring sail
#

Hi guys, it's been a while since the last time I used unity, when I use visual studio code, it shows me the following warning that is wrong and doesn't make sense, I already searched the internet and I still can't find how to fix it, does anyone know how to eliminate those false warnings of unused methods?
PS: I swear to god that if someone suggests "regenerate project files" I will completely ignore it because I have already tried that ad nauseam

somber nacelle
#

make sure that it is configured. those can also be ignored since unity will call those methods automatically

#

also maybe consider switching to a real !IDE that is actually supported

tawny elkBOT
#
๐Ÿ’ก IDE Configuration

If your IDE is not autocompleting code
or underlining errors, please configure it:

โ€ข Visual Studio (Installed via Unity Hub)
โ€ข Visual Studio (Installed manually)

โ€ข VS Code*
โ€ข JetBrains Rider
โ€ข Other/None

*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.

timid badger
#

hello guys, so i am making fps game and i wanna make the skin and animations invisable to me and appears to the other guys in the game so what can i type in search to have a tutorial im using photon pun 2

thorny spindle
#

I'm not sure where to ask this

#

But when I add a rigidbody to an object I have with a mesh collider

#

the mesh collider seems to 'diseappear'

#

as in the wireframe disappears

#

Why would this happen?

#

Is it because it's non-convex?

#

Turning the IsKinematic seems to make it come back

cosmic rain
lean sail
#

you should get an error for it in the console

#

or a warning at least

ashen yoke
#

either unity decided that mesh wire has to have higher order, so it draws over collider wire, or that its redundant because they are equal

orchid bane
#

How do you get an object from a higher container in Zenject?

cobalt gyro
#

what are the absolute value brackets used for

prime sinew
cobalt gyro
ashen yoke
#

what is " absolute value brackets "

latent latch
#

for absolute values obv

lean sail
#

the ||?

ashen yoke
#

i can only find this

#

which is string.Format formatting

#

wait no, its not

pure cliff
#

You should typically just register all your stuff globally for a DI engine, and can inject anything into anything

orchid bane
pure cliff
orchid bane
#

Registered

pure cliff
#

cuz you should be able to just inject the same thing into the child as well

#

if you want them to both be the same instance of the same thing, you want it registered as a single (I pretty much register all my stuff as singles, I very rarely need anything other than singles)

orchid bane
#

I wanted to bind an interface to it only in the child container

pure cliff
#

Or well, as a single or FromInstance

pure cliff
orchid bane
#

Bind<IInterface>().FromParentContainer<MyClass>

#

Looks like a stupid idea tho

pure cliff
#

it sort of violates the point of doing all this stuff, that you should just be designing your components to be standalone individually and they shouldnt "care" who calls them or who they call, they just do their own job

daring sail
#

@somber nacelle i read one of the links that you share (ttps://code.visualstudio.com/docs/other/unity) there was the solution!, it took it took a little time to understand it and implement it but finally I did it, thank you very much for passing on the information

torpid beacon
#

I am trying to setup a__ one-way platform__ script. The downward input will call on Physics2D.IgnoreCollision between the player collider and the platform collider. I set IgnoreCollision back to false in the "OnCollisionExit2D" call. For some reason, OnCollisionExit2D keeps being called right after OnCollisionEnter2D. I am lost as to why.

lean sail
tawny elkBOT
#
Posting code

๐Ÿ“ƒ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

๐Ÿ“ƒ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

torpid beacon
dusk apex
opal cargo
#

How would you guys implement a ledgeclimb?
By using fancy trigonometry raycast to determine if a ledge starts/ends or just use a collider which tells the climbable area via `extends?

dusk apex
#

Define ledgeclimb

opal cargo
#

Holding onto a ledge, move left/right till end of ledge, climb upwards or let go/fall off.
At the moment I'm doing a raycast above/infront of player with direction down to look for a reachable higher ground. Next I'm doing a raycast forward at the height of the previous cast to get the wall position. After that, I'm lerping to the desired position on the wall.
Now I want to climb left/right to the edges of the wall but can't figure out an easy way

dusk apex
#

Assuming you've got some working ledge hang feature implemented, you could simply allow movements to the left and right whilst hanging or climb above. I'm not really sure what you're asking.

opal cargo
dusk apex
#

So it's about ledge hanging then. You could either use a collider with callbacks or shoot a few more rays to check if area is valid for hanging.

opal cargo
#

I want to travel a fixed distance for every button press and play an animation (0.5f).
I could do a raycast at the destination and see if there's still wall to hang on to. But if not, how do I calculate the remaining distance to the end of the wall?

#

Cut destination distance in half, do another raycast, cut again in half and so on?

dusk apex
#

Maybe allow it to fully animate but do not translate the position - assuming you aren't changing the position using animation.

opal cargo
#

No, I want to keep that seperate (guess otherwise it would be root animation?)

#

Just want to avoid that my character ledge hangs through the air

dusk apex
#

Looks like a very specific design, good luck - truly.

opal cargo
#

It should be like something you see in the old Tomb Raider games honestly ๐Ÿ˜‰

#

Guess I will try something like

// Is there wall at the desired destination
// Is there an appropriate angle on the wall to grab onto
// If not, cut distance in half and check again
// If hit, increase distance by half and check again...
#

A lot of Raycasts, hope it doesn't take too much performance

orchid bane
#

When I spawn things with Zenject they get childed to the container they originated from, but in my case the container is on the enemy. When I spawn loot from enemies and destroy enemies, loot gets destroyed too. Any solutions?

opal cargo
orchid bane
#

Will work, but it's a bit complicated, isn't it?

opal cargo
#

Enemy signals a createLoot() to the manager, it creates loot at position of the enemy with desired loot told by the enemy before he dies.
Kinda like createLoot(position, List<lootTypes> lootList)

orchid bane
#

Yeah I get it

#

But then loot won't be able to get anything from enemy's container if needed

opal cargo
#

Maybe you shouldn't destroy an enemy by deleting it, just deactivate it?

orchid bane
#

Doesn't sound like a good idea

opal cargo
#

Why not?

orchid bane
#

Because because of drop?

opal cargo
#

Don't you have an enemy manager that takes care of all enemy instances?
What do you mean by drop?

orchid bane
#

Coins

#

Meat

#

I do have an enemy manager

#

But it doesn't manage loot at the moment

pure cliff
#

Make a LootManager or whatnot and "bubble up" the enemy death as an event, which triggers your LootManager to spawn loot

opal cargo
# orchid bane But it doesn't manage loot at the moment

So the type of loot that's dropped is stored in the enemy unit, which is known by the manager.
Before the manager "kills" (deactivates) the enemy, it can send a dropLoot to the itemManager, which also deletes the loot after it got registered by the player inventory. Don't know your code, but this seems not too complicated

ivory igloo
#

how would I fix this?

tired elk
#

The scale doesn't have anything to do with your normal. It should always be perpendicular to your surface

#

Normal interpolation, if i'm not mistaken, is a "mean" between multiple normals

ivory igloo
tired elk
#

What do you use to draw your debug line ?

ivory igloo
#

Debug,DrawRay

tired elk
#

Can you show me the call to DrawRay pls ?

ivory igloo
#

I didnt change any line I was just testing it

tired elk
#

Oh ok, my bad

#

Thought you adapted it

#

I think that's because the ray is not supposed to be your normal. What the example do is draw a line between your mousePosition and your surface barycenter when your mouse is over a the collider

ivory igloo
#

Yet the Vector is called "interpolatedNormal" and at uniform scaling it returns a perfectly usable normal?

tired elk
#

I'm actually confonding DrawLines and DrawRay, the second argument is not a position but a direction, my bad

ivory igloo
#

the comment says DrawLine but the function is a Draw Ray

rotund burrow
#

I'm making a player ability (it's on button press) that will have dynamic mesh generation for visuals, depending on player input. How should i do class structure or where to put what code?

ivory igloo
#

would be alot better If i knew how to get the actual scaled normals rather than this bandaged solution so I could also use it with skewed meshes but oh well

leaden ice
gentle aspen
#

Hello, I am creating a meditation VR app.
While scripting the timer, I noticed that the TMP is not compatible with my script but legacy text works just fine.
Has anyone else had this problem and knows how fix this?

thin aurora
#

In this case, the variable must be of type TMP_Text

gentle aspen
real sequoia
#
  1. In my project, I have an "Edge Collider 2D" component, which is essential for triggering an event that spawns platforms for the player to jump on.
  2. The function "SpawnMultiplePlatformWithEnemyProbability" is responsible for spawning several platforms, precisely eight platforms in my case, each separated by a vertical distance of "2.6f." Inside this function, a for loop will run, for spawning these platforms.
  3. The variable "nextSpawnPlatformPosY" will store the y position for the next spawning platform, and it will be updated within the "SpawnMultiplePlatformWithEnemyProbability" function.
  4. In our situation, "nextSpawnPlatformPosY" will hold the value of the top platform's y position minus"2.6f." [Because it holds the value of the next platform y position]
  5. The objective is to shift the offset of the EdgeCollider2D from the top platform's position to a some position below it.
  6. In this case, Unity will call the "SpawnMultiplePlatformWithEnemyProbability" function and proceed further without waiting for its completion.
  7. If, during the ongoing execution of the "SpawnMultiplePlatformWithEnemyProbability" function, we attempt to retrieve the value of "nextSpawnPlatformPosY," it will not provide us with the top platform's value. I hope this explanation is clear.
  8. My question is, how can I ensure that I wait for the "SpawnMultiplePlatformWithEnemyProbability" function to complete before proceeding further? So that my logic work as excepted in any scenario.
real sequoia
#

@ashen yoke
Thank you for your response. After conducting some research, I came across coroutines, where people use "yield return null;" to pause for one frame. However, I'm not entirely clear on the concept. Could you provide some examples to help me understand it better?

ashen yoke
#

coroutine runs asynchronously, you can suspend execution with yield indefinetely until some condition you want is satisfied

#

you can chain coroutines so one awaits another

#

IEnumerator WaitForSpawn()
{
  int countLeft = 10;
  while(countLeft > 0)
  {
     yield return StartCoroutine(Spawn());
     --countLeft;
  }
  Debug.Log("All spawned");
}

IEnumerator Spawn()
{
    Instantiate...
    while(!completedSpawn)
    {
        yield return null;
    }
}
real sequoia
#

private IEnumerator Seq()
{
yield return StartCoroutine(ExplodeCar());
yield return StartCoroutine(CrowdReaction());
yield return StartCoroutine(WinningCelebration());
}
like this right? I found it on stackoverflow.

ashen yoke
#

this will run them sequentially one after another waiting for each to complete yes

real sequoia
#

Thanks for guiding me in the right direction, much appreciated.

steady moat
#

Real question, do you need the StartCoroutine ? Or you can do yield return Spawn()

#

I just started a build without doing the StartCoroutine, hope it works.

steady moat
#

I base myself on yield return Mount(user, Dialogs.DialogType.Load, (LoadSaveResult result) => mountResult = result);

#

Which is working

#

๐Ÿค”

ashen yoke
#

this should only work until first yield

steady moat
#
 while (response.Locked)
      yield return null;
#

This is the yield

ashen yoke
#

hm

steady moat
#

I've been using this for a while.

steady moat
sage latch
#

But if you want to cancel the routine you do need the Coroutine object it returns

ashen yoke
#

@steady moat check this out

#
    IEnumerator Test()
    {
        IEnumerator[] wait1000Frames = new IEnumerator[1000];
        yield return wait1000Frames.GetEnumerator();
    }
steady moat
#

What is the result ?

#

Does it truly wait ?

ashen yoke
#
    IEnumerator Test()
    {
        object[] wait1000Frames = new object[1000];
        yield return wait1000Frames.GetEnumerator();
    }
#

yep

steady moat
#

I'm not really in a position to test right now

#

oh nice.

ashen yoke
#

just did

#

im using mec and always sticking with running coroutines through Run, assumed unity would also enforce something but returning any enumerator works it seems

#

yeah why wouldnt it

#

at the top level its most likely just a ```cs
foreach(YieldInstruction i in coroutine)

steady moat
#

It makes sense, this is not even Unity tricks

ashen yoke
#

yeah

real sequoia
#

I made an interesting discovery just now. If you call a coroutine function just like a regular method, it will execute as a normal function, and the yield return statements will not work. I thought it was relevant to share this information since we were discussing coroutines.

sage latch
#

That doesn't sound right

ashen yoke
#

that is correct

sage latch
#

By coroutine function you mean it returns IEnumerator right?

real sequoia
#

correct

sage latch
#

The enumerator you get back is enumerating over the code in the method

#

But if you never call MoveNext on it (enumerate it) it shouldn't execute, right?

ashen yoke
#

yep its skipped

sage latch
#

Yeah, it doesnt do anything

leaden ice
#

THis is basically how coroutines work under the hood

#

and it will explain your observation

real sequoia
#

Thank you for sharing, it is really informative, I will definitely go through it.

ashen yoke
#
    private void Start()
    {
        IEnumerator t = TestCoroutine();
        while(t.MoveNext())
        {
            Debug.Log(123);
        }
    }
    IEnumerator TestCoroutine()
    {
        Debug.Log("0");
        yield return new WaitForEndOfFrame();
        Debug.Log("1");
        yield return null;
        Debug.Log("2");
        yield return null;
        Debug.Log("3");
    }
#
    private void Start()
    {
        TestCoroutine___ t2 = new TestCoroutine___();
        while (t2.MoveNext())
            Debug.Log(123);
    }

    class TestCoroutine___
    {
        public int index;
        public object current;
        public bool MoveNext()
        {
            switch (index)
            {
                case 0:
                    index++;
                    Debug.Log("0");
                    current = new WaitForEndOfFrame();
                    return true;
                case 1:
                    index++;
                    Debug.Log("1");
                    current = null;
                    return true;
                case 2:
                    index++;
                    Debug.Log("2");
                    current = null;
                    return true;
                default:
                    Debug.Log("3");
                    return false;
            }
        }
    }
#

yay i did the work of the compiler

steady moat
#

No need for a compiler anymore

autumn cipher
#
player.playerInput.actions["Look"].performed += OnLook;```
do I have to unsubscribe input events manually in OnDisable() or does Unity automatically do it?
ashen yoke
#

most likely you have to

#

cant imagine how unity would deduct your intent

#

and what mechanism would do it, since you are not binding it to a specific monobehaviour

ashen yoke
#

but you can disable/enable the whole action map in Enable/Disable

#

or the action itself, im going from the docs

autumn cipher
#

I see

#

thank you both

opal cargo
#

Does anyone have an idea how I can check when a platform I'm moving on will end, so I can limit the movement distance?

#

Want to avoid to send Raycasts constantly and maybe pre-calculate the destination

leaden ice
ashen yoke
#

Sphere/Capsule casting

opal cargo
leaden ice
#

prefabs!

#

Otherwise you are likely to have to do some kind of raycasting/physics query

opal cargo
ashen yoke
#

find furthest intersect, filter by collider of the platform, get furthest approximate edge

opal cargo
ashen yoke
#

SphereCastAll is one op

#

which does whats on the picture

steady moat
#

Is the tracjectory known and static ?

leaden ice
#

I would probably do a raycast downwards from a position slightly in front of the character

#

and possibly binary search my way into finding the edge

ashen yoke
#

use this instead

#

sphere cast would project a wide testing tube in into velocity, more reliable imo

#

can use Capsule cast instead

opal cargo
#

Will try it, does it also recognise the exit point of the wall collider?

ashen yoke
#

i dont understand

opal cargo
#

I understand your proposal like this

ashen yoke
#

your initial question i understood as "finding the platform edge"

opal cargo
#

Like I do a CapsuleCastNonAlloc in front of my player (inside the wall) and check for the furthest distance

ashen yoke
#

you do capsule cast from player towards velocity vector, usually no gaps

#

you get bunch of intersection points, you analyze them

barren void
#

How do I pass in the value of my slider to this function? Cause right now its always giving me '0' despite the slider was set to the max value

opal cargo
ashen yoke
#

you can use it for finding floor edges, walls, next position, lots of stuff

opal cargo
ashen yoke
#

you can test the collider

#

if you know the collider you are standing you can filter out all points unrelated to that collider

opal cargo
#

Right

ashen yoke
#

i see what you mean, yes you can find gaps between colliders, but note that the RaycastHit[] results are not ordered by distance

#

youd have to sort/split into groups by collider, find closest points between 2 groups to find gap span

#

probably

opal cargo
#

Hmm, documentation says For colliders that overlap the sphere at the start of the sweep, RaycastHit.normal is set opposite to the direction of the sweep, RaycastHit.distance is set to zero, and the zero vector gets returned in RaycastHit.point.
So when starting the sweep inside the wall, I wouldn't get any distance?

ashen yoke
#

why do you start it inside the wall

#

should start inside the player, imo

opal cargo
#

When I start inside the player I wouldn't touch anything

ashen yoke
#

what it would do is do full sweep so you actually get the points intersecting with the wall

opal cargo
#

I've got an origin and a direction in which the player should move, by sweeping just over the surface the player is attached to, I won't hit anything

ashen yoke
#

start from player, add some offset to the cast

#

shell distance

opal cargo
#

Maybe this makes it a bit clearer of what I'm trying to do.
The red capsule is the player, moving alongside the (blue) wall-normal in 0.5f steps, green is a ground layer.
A sweep at the origin of my player into the direction the player wants to climb won't hit anything, since the cast would be next to the wall too (as my player).
Or I'm getting something completely wrong about the CastAll functions

ashen yoke
#

use this

opal cargo
swift falcon
#

Hello! How are you? I have a problem with Unity. I'm very new to this, and I don't know how to solve it. When I create a script with C# and try to use the Time.deltaTime function, it doesn't work for me. Could you help me with that? Thank you!
error: Assets\Scripts\PlayerControler.cs(16,9): error CS0103: The name 'time' does not exist in the current context

opal cargo
#

This is what happens right now, just moving further and further.
But yeah, will try the Casts, maybe that's a solution.
Otherwise I have to bite the bullet and use empty game objects

ashen yoke
swift falcon
#

it's like it doesn't detect it.

ashen yoke
languid hound
#

Docs say I can include a true or false param to define wherever it includes inactive objects
GameObject.FindObjectsOfType<FastAccess>(true);
This gives an error saying No overload for method FindObjectsOfType takes 1 argument

#

Oh wait

#

I created my project with the wrong Unity version smh

leaden ice
tawny elkBOT
#
๐Ÿ’ก IDE Configuration

If your IDE is not autocompleting code
or underlining errors, please configure it:

โ€ข Visual Studio (Installed via Unity Hub)
โ€ข Visual Studio (Installed manually)

โ€ข VS Code*
โ€ข JetBrains Rider
โ€ข Other/None

*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.

swift falcon
swift falcon
leaden ice
#

I linked you the instructions

swift falcon
ashen yoke
#
public Vector3(float x, float y);
public Vector3(float x, float y, float z);

swift falcon
#

thank you

ashen yoke
#

that issue is compiler panicing, most likely

#

one error cascades because you broke syntax

#

happens in some scenarios

#

cant say for sure because your IDE is broken on the screenshot

cobalt gyro
#

i completley forgot about the OR operator

autumn cipher
#

what is the priority of the new input system's update call?

#

is it before or after Update() ?

#

I mean logically it must be before the regular Update()

formal igloo
#

I'm using dotween, which I like very much and use all the time. I want to use the Elastic easing. The amplitude of the easing is way too high. They seem to allow arguments that should control the easing, but from what I can tell, anything I pass in there makes the amplitude bigger? Anyone encounter this before? What am I doing wrong?

#

I've tried values everywhere from 1.000001f, to .000001f, to .99999f, to 10f, to -10f

green oyster
#

guys my unity is just not responding, and i cant open it, is there a way to stop the game running coz theres probably an infinite loop running

#

or i just gotta restart unity?

uneven monolith
green oyster
#

alr

rain minnow
#

force close with task manager . . .

uneven monolith
#

?

#

Thats what ive done last couple of years

#

When stuff crashes/starts lagging too much

fluid crag
#

Has anyone ever encountered an error where a variable is correctly printing out a gameobject value, but then when another method in that class is ran, that same variable is returning null?

rain minnow
fluid crag
rain minnow
#

we need more info. post the !code with the event . . .

tawny elkBOT
#
Posting code

๐Ÿ“ƒ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

๐Ÿ“ƒ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

green oyster
#

What kind of magic is going on

#

why does this keep on looping infinitetly?

#

"barsetting.numberofbars" is always 19.

#

and then, ```cs
while (BarContainer.GetChildren().Count > barSetting.numberOfBars)
{
List<GameObject> bars = BarContainer.GetChildren();
Destroy(BarContainer.GetChild(bars.Count - 1).gameObject);
}

potent sleet
rain minnow
#

the condition must be false in order to exit . . .

green oyster
#

"BarContainer.GetChildren().Count" this bit initially is 20, but for whatever reason, never reduces?

#

even tho im destroying one of the chidlren inside of it

green oyster
#

as it keeps on looping

#

it reminas same 19

#

and the count of bars still is 20

#

each time it loops, so is it no destroying the child of barcontainer?

rain minnow
#

is BarContrainer an argument of this method?

green oyster
#

no, its just a transform that ive assigned in editor

#

its the object that contains all my bars

#

this is hella weird, and it makes my game crash coz it keeps on infinitely looping

#

but i dont know why it keeps looping, its not destroying the object?

rain minnow
#

can you show the entire method?

green oyster
green oyster
# green oyster

quick Q but u see the "HandleNumOfBarsChange" here, unity will exceute it fully right

#

before moving onto next line

rain minnow
#

you need to add StartCoroutine to make it a coroutine . . .

green oyster
#

before moving on to the next line? right?

rain minnow
#

nope . . .

green oyster
#

ok so its good that i added the coroutine coz i need it to fully execute before moving on

green oyster
pure cliff
#

summarized though:

yield return StartCoroutine(A());
yield return StartCoroutine(B());

B() wont start until A() is over, wrapping method wont end til both are done

var a = StartCoroutine(A());
var b = StartCoroutine(B());
yield return a;
yield return b;

A() and B() run in parallel, wrapping method wont end til both are done

StartCoroutine(A());
StartCoroutine(B());

A() and B() will run in parallel, wrapping method ends asap

green oyster
pure cliff
#

Personally I prefer Tasks though, they dont seem to be quite as a performant as Coroutines, but in return they have a tonne of handy utility methods and make more sense

#

instead of yield return you just use await, and you get stuff like await Task.WhenAll(...) and await Task.WhenAny(...)

green oyster
#

welp still getting infinite looping

pure cliff
#

prolly an enumeration thing

green oyster
#

For some reason i cant see the value of that

pure cliff
#

Why dont you just do a for loop?

#

or sorry actually Id just do .Skip

green oyster
#

well, while loop is just the first thing that came to mind lol

pure cliff
#

BarContainer.GetChildren() does this return them in the right order?

#

if so you can just do BarContainer.GetChildren().Skip(barSetting.numberOfBars) to get all the ones that require deleting

green oyster
#

yes they in right order

#

wait so, what does skip do, it basically gets all items in a list after a certain index?

pure cliff
#

yeah it "skips" that many in the list

green oyster
#

Ah i see

pure cliff
#

You also can use .Take which takes that many

green oyster
#

alr thanks, i will do that, never knew about skip

leaden solstice
#

Destroy does not happen immediately

pure cliff
#

so if you specifically wanted say, the 6th to 10th(inclusive) items you could do

.Skip(5).Take(5)

green oyster
#

oh well, ima go with the .skip way then

#

seems better

icy inlet
#

I have a fully built AddForce physics based movment system and am now experiencing a very dumb and obvious bug. for reference here are moves that the player can do to increase their momentum (which is at the core of the game):

  • Jumping - Not only upwards, but it pushes the player forwards
  • Sliding - it pushes the player forwards and slides the player on slopes
  • Dodge - it pushes the player in the direction they are facing

Now. The problem occurs when the player presses multiple of the same button. The statemachine changes very fast and triggers all 3 addforces if prompted by the player. This is undesirable because it makes the player suddenly go at 24 km/h speed.

How can I get rid of this without fundamentally changing those mechanics - the player has to be able to dodge and slide every time during play, jumping isnt AS important, but they still have to jump during those states too - now what??

green oyster
#

How do i set prevbar to barsettings, but not like reference to it?

#

if u know wahtim saying

#

i dont want bar setting to be updated if i change prevbar setting values

#

i want prevbar setting to be its own bar setting, but just has its settings set to bar setting here once

icy inlet
#

Make a new bar setting and assign the values accordingly?

brazen narwhal
#

Hello, does anyone know how to add a scalebar to Mapbox Unity sdk specifically on its zoomable map?

icy inlet
#

prevBarSetting = new BarSetting(barSetting); but idk if thats possible

green oyster
icy inlet
#

Well you can just make a new set of values and set them one by one but thats nasty

#

I dont think there is a different way to completely copy an object instead of making a reference to it

rain minnow
green oyster
#

my script

rain minnow
#

we can't tell you how to make a copy (or if you can) without knowing what the type is . . .

icy inlet
#

Oh that too yeah

rain minnow
#

BarAudioVisualizer doesn't tell us anything. is it a class, struct, poco, MonoBehaviour?

green oyster
#

be able to get copied

rain minnow
#

so BarSetting can be copied . . .

dusk apex
#

Copy constructor?

rain minnow
#

just create a ctor that copies all of its values to the new instance . . .

icy inlet
#

You cant new() that shit?

#

Just copy contructor

rain minnow
#

or a copy ctor . . .

green oyster
dusk apex
#

Or make it a struct

icy inlet
#

Thats the same thing lil bro

green oyster
#

i cant new() the object lol i tired

rain minnow
#

personally, i agree with Dalphat. just make it a struct, especially, since it has a few fields and they're all value types . . .

icy inlet
#

Thats a mind shortcut you dont just new() an object lmao

dusk apex
icy inlet
#

Just make a struct out of it thats better

green oyster
#

Ok, and struct can be copied?

icy inlet
#

A normal class can too yeah

green oyster
#

simply by doing obj = obj?

icy inlet
#

Yes

green oyster
icy inlet
#

My brother

#

Do you know how creating new class objects works

rain minnow
green oyster
#

i want to assign the prevBarSetting object to another object

#

basically copy its values

icy inlet
#

copiedClass = new ClassName(...stuff that the constructor needs..);

#

But yeah struct is way better

#

If you need only values

green oyster
#

i will do the copy constructor coz that actually does waht i wanted

icy inlet
#

How does struct not do what you wanted :33

green oyster
#

hmmm

#

ok i will tyr sturct first

icy inlet
#

Its a little more clearer than constructors

#

Constructors are useful when you have functions within a class

dusk apex
icy inlet
#

When the class object is instantiated you can provide values that it works off

icy inlet
#

I always use contructor workflow so that i can keep an instance of the class and assign values to it

#

Like a little notepad

copper blaze
#

is it good practice to separate out player animations into a separate script? (currently have it in same script that handles movement)

steady moat
orchid bane
green oyster
#

of ur github lmao

orchid bane
#

What should I change it to...

quaint crypt
#

is there a way to know which meshes take up most gpu rendering time?

radiant estuary
#

Hello having a bit of trouble with saving/loading system.
Basically i've gotten to a point where my game saves/loads fine inside the Unity play mode. But when I upload the game onto github pages or itch.io, saving seems to not be working anymore.
Pretty sure the problem is in Application.persistentDataPath, but I don't know what to replace it with.

Code is in C# and the build is WebGL

leaden ice
topaz sapphire
#

How should I handle recoil in an fps? should I have 2 rotations stored, one being the true rotation and the other being the one affected by recoil, add recoil to the recoil rotation and have it slerp back to the true rotation?

leaden ice
sleek bough
#

@green oyster There's no off-topic here

leaden ice
#

e.g.

PlayerBody // < this one rotates left/right (y axis rotation) with player input
  CameraRig // < this one looks up and down (x axis rotation) with player input
    Camera // < this one rotates for the recoil, and always reverts back to (0,0,0)
topaz sapphire
#

problem is I have a bunch of code that uses specific calls using transform.parent(x amound of times)

#

so I think Ill just use one script

leaden ice
#

and there's no need for multiple scripts

topaz sapphire
#

cant I just attatch a script to my camera that handles the recoil?

#

or is there a problem with doing that directly to a camera?

leaden ice
#

you can attach your script to whatever object you want

#

my solution had nothing to do with which object the script is attached to

leaden ice
radiant estuary
leaden ice
spark shore
#

is it ok to use a SpriteRenderer to render an image within 3D scene, instead of using a canvas and setting it to world space? Thank you

flint needle
#

how do you set a blend time for a specific virtual camera?
like the transition between whatever camera and the said camera is x seconds.
can i set this in the said camera without worrying where the blend comes from?

topaz sapphire
#

but It may work

vestal crest
#

hi, im working on photon fusion and I am using cinemachine. When player spawns camera sets follow to that player. camera is not network object and class is monobehaviour. My issue is when a player spawns on my host's camera sets follow to client. how to fix it?

#

im confused with that

somber nacelle
#

only activate the vcam on the local player's machine

trim ferry
#

im trying to change the speed of an specific animation, but this changes the speed of everything, how do i change the speed for only 1 animation??

vestal crest
somber nacelle
#

check the photon docs

wary coyote
#
                    if (originalMesh == null)
                    {
                        Debug.Log($"Error - {meshFilter.name} does not have a sharedMesh!");
                        continue;
                    }

                    Mesh meshCopy = Object.Instantiate(originalMesh);
                    UpdateMesh(meshCopy);
                    string fileName = Path.GetFileNameWithoutExtension(assetPath);
                    string newAssetPath = Path.Combine(destinationPath, fileName + "_" + meshIndex + ".asset");
                    if (AssetDatabase.LoadAssetAtPath<Mesh>(newAssetPath) != null)
                    {
                        Mesh existingMesh = AssetDatabase.LoadAssetAtPath<Mesh>(newAssetPath);
                        EditorUtility.CopySerialized(meshCopy, existingMesh);
                        EditorUtility.SetDirty(existingMesh);
                    }
                    else
                    {
                        AssetDatabase.CreateAsset(meshCopy, newAssetPath);
                    }
                    AssetDatabase.SaveAssets();

what are possible reasons why changes to my meshes are not updating my meshes?
In the above code, if I delete the mesh and make unity create a new one from scratch, it comes out as expected.
However if I do not delete the mesh, the above code won't change the resulting mesh. I am specifically editing the meshes vertex colors

rain minnow
wary coyote
#

What is different about ```
AssetDatabase.CreateAsset(meshCopy, newAssetPath);

that is not occuring when I do?
                    Mesh existingMesh = AssetDatabase.LoadAssetAtPath<Mesh>(newAssetPath);
                    EditorUtility.CopySerialized(meshCopy, existingMesh);
                    EditorUtility.SetDirty(existingMesh);```
wary coyote
#

EditorUtility.CopySerialized(meshCopy, existingMesh); - maybe my changes arent considered serialized?

#

so the copy method doesnt carry them over the way making a new one from scratch would? My changes are writing to the vertex colors in this use case

icy inlet
#

Lowering the clamp is just a bandaid

vestal crest
# somber nacelle check the photon docs

i already checked and again checked but I still couldnt managed to make it. Should i make my vcam network object or not? Is my logic wrong? checking if local player is wrong idea?

swift falcon
#

If I have an array of a class type, does Array.CopyTo create copies of the values as well, or will I just end up with two arrays that reference one set of objects in memory ??

vestal crest
#

what i want to achieve is one camera in scene and set to local player

somber nacelle
vestal crest
#

.d i just kindly ask my questions and you are saying maybe its not for you lol

somber nacelle
rain minnow
vestal crest
#

if you dont want to help me okay dont help me as i said i already checked and couldnt manage to make it work. sorry if im in wrong text channel.

somber nacelle
#

multiplayer is not a simple topic and beginners who don't know how to read docs really shouldn't be attempting it. if you want to continue brute forcing your way through it, then go for it ๐Ÿคทโ€โ™‚๏ธ

rain dove
# radiant estuary Hello having a bit of trouble with saving/loading system. Basically i've gotten ...

just a suggestion; pls avoid using capital letters while saving files or reading files; ill give u the reason: i was recently working on an ios development; and i would execute a command to create a directory at persistent data path by name "Sample" and it would create it by the name "sample" later when i run the debug log to check if the directory that i just created exists or not; it would throw me with a false; also the same issue happens on spcific manufacturers of android devices as well

buoyant valve
#

So I've been trying to find a solution for a long time and still not sure how to fix this issue. I have two camera, one that has post processing and another to ignore post processing on certain objects that use the layer
IgnorePostProcessing. The problem is any object that is ignored by post processing camera is causing fog to not be applied to these objects. Not sure if this is a unity bug or if I need to change something?
I have attached both the camera settings.

wary shell
#

simple simple question
heres some code

side = new string[] { "Black", "White" }[rand.Next(1)];```
to pick a side randomly. Now, sometimes, for some reason I CANNOT figure out, side = "Whitee" and I tried to figure this out for so long and I cant begin to think of a reason why
somber nacelle
#

well it wouldn't be that line of code that sets side to "Whitee". however, i do have to ask why you've decided to create an array there if you're just choosing between two elements. especially if you're doing this often. just use a ternary for that or at the very least instantiate the array only once instead of every time you need to choose a random object

wary shell
#

well I only have to choose a side once

somber nacelle
#

okay well then you're still instantiating an array unnecessarily. unless this isn't your actual code and is just meant to demonstrate what is happening

wary shell
#

no for now it is the actual code - i should use a ternary for this?

somber nacelle
#

for this specifically? yeah probably. as for your issue, you'll need to show more code because neither of the strings in the array are "Whitee" so that line of code is not assigning that string to your side variable

wary shell
#

actually yeah now that you mention it that's probably not it

#

let me show you all of the function here

#
if (host)
        {
            System.Random rand = new System.Random();
            side = new string[] { "Black", "White" }[rand.Next(1)];
            Debug.Log("Side: " + side);
            enemySide = side == "Black" ? "White" : "Black";
            SteamMatchmaking.SendLobbyChatMsg(new CSteamID(m_SteamIDLobby), Encoding.UTF8.GetBytes("SIDE/" + enemySide), 1024);        
        }```
(this runs on both machines, assuming there is one host)
#

theory - its something to do with the fact i gave it 1024 bytes

#

anyhow, whatever it is, i still get "Whitee" when decoding the message

#

I decode it like so:

byte[] message = new byte[1024];
SteamMatchmaking.GetLobbyChatEntry(new CSteamID(m_SteamIDLobby), (int)data.m_iChatID, 
            out CSteamID sender, message, 1024, out EChatEntryType type);
string messageString = Encoding.UTF8.GetString(message);
Debug.Log("Chat message update. message: " + messageString);```
lean sail
wary shell
#

i think i fixed it hold on

lean sail
#

I doubt the bytes are the problem, 1024 is a lot

#

For what you're trying to send

wary shell
#

i changed 1024 bits to the length of the encoding

wary shell
#

maybe thats screwing it up idk

wary shell
#

ALRIGHT making the byte size array lesser worked from the "Whitee" thing but brand new problem - the converted from UTF8 byte[] string now cannot equal anything else
Four logs

Debug.Log("side == White:");
Debug.Log("Side: " + side);
Debug.Log("Class of side: " + side.GetType());
Debug.Log(side=="White");```
Output attached
![sad](https://cdn.discordapp.com/emojis/941201178170105876.webp?size=128 "sad")
somber nacelle
wary shell
#

no man

#

not like this

somber nacelle
#

Debug.Log($"'{side}' is equal to 'White' ? {side == "White"}"); this will show you what i mean

wary shell
#

testing this vigorously one sec

#

dont ask me why how or when but it output this
'White

somber nacelle
#

screenshot it

wary shell
#

idk whats going on

somber nacelle
#

๐Ÿค”

#

click it and show the entire message + stack trace

wary shell
#

is this what you mean?

somber nacelle
#

yeah. and that line was exactly the line i gave you?

wary shell
lean sail
#

i think its some c++ issue then with the amount of bytes u are giving

#

what did u change it to

wary shell
#

length of the bytes sent

lean sail
#

oh this is different

wary shell
#
byte[] enc = Encoding.UTF8.GetBytes("SIDE/" + enemySide);
            SteamMatchmaking.SendLobbyChatMsg(new CSteamID(m_SteamIDLobby), enc, enc.Length); ```
#

it is the ascended string, it screws up everything else

quartz folio
#

It's probably just got the null terminator in it

wary shell
#

that sounds cooler then what it probably is

#

lemme look it up

#

huh

#

a c++ thing

#

can i even handle it in c#?

lean sail
#

theres probably just a different method u have to do for sending/receiving steam messages. I chose to use facepunch instead cause of stuff like this

wary shell
#

also i just had an idea

somber nacelle
#

should be able to just trim the \0 character

wary shell
#

thats my next excursion

wary shell
#

yeah that didnt work

#

facepunch it is, we are starting over peoples

lean sail
#

that shouldve worked although I couldve sworn the examples ive seen just didnt have to deal with this, what did you type?

wary shell
#

message was SIDE/(side) and it seems to really mess things up when i split it by "/" and look at the [1] slot

lean sail
#

should just be fine to do .Trim('\0')

somber nacelle
#

tested it myself. if there are null terminator chars at the end of the string that will remove them. if that isn't the character in the string that wouldn't do anything though

wary shell
#

BTW congrats this is the weirest programming error i have ever had

#

i guess this is what happens when you mess with networking

lean sail
wary shell
#

added side = side.Trim('\0');

#

wait

#

check it

somber nacelle
#

print out what characters you are receiving cast to int so that you know exactly what whitespace characters there are

lean sail
#

at this point id just print out each byte of the string and see what it is

wary shell
#

they sent the length of the bytes +!

#

+1

#

nope didnt work either

lean sail
#

honestly got no clue why they do, just one of the drawbacks to using steamworks.net since its written in c++. You'll always have to do some workarounds
Facepunch at least is more concise code but the uh documentation... ๐Ÿ‘ป

wary shell
#

we'll deal, thanks anyways people

swift falcon
#

what should i use for sending long blocks of code

somber nacelle
#

!code

tawny elkBOT
#
Posting code

๐Ÿ“ƒ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

๐Ÿ“ƒ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

rocky basalt
#

If anyone has suggestions I'd appreciate it

alpine lava
#

Hey, does anybody know of a way to translate the movements of a real life camera into unity to animate a unity camera.

#

I'm trying to find a better way of animating a first person cut scene.

rocky basalt
alpine lava
#

Well im using MOCAP gloves to track the hands of the cut scene and i was wondering if i could use a camera to do the unity camera equivalent

#

And i dont have a VR headset

rocky basalt
#

buying a VR headset might be the cheapest way of doing that tbh. Unless you wanna strap your mocap glove to your face lol

alpine lava
#

Okay, thanks i will look into it

primal wind
#

I think there are apps that can track a person on a video then from that, use a simple rig then just slap a camera on its head

#

Tho idk any

#

I just know they exist

civic igloo
cobalt gyro
#
    {
        Vector3 dir = MyInput.Direction(target, origin);
        /*This line is giving me errors*/GameObject projectile = GameObject.Instantiate(item.bulletPrefab, origin, Quaternion.identity);
        Rigidbody2D rb = projectile.GetComponent<Rigidbody2D>();
        Bullet bullet = projectile.GetComponent<Bullet>();

        bullet.item = item;
        rb.AddForce(dir * item.gunInfo.bulletSpeed);
    }``` ```public void ProjectileExplode()
    {
        GlobalWeaponHandler.ProjectileShoot2D(hitVec3, hitVec3 + Vector3.up, secondaryItem);
        GlobalWeaponHandler.ProjectileShoot2D(hitVec3, hitVec3 + Vector3.right, secondaryItem);
        GlobalWeaponHandler.ProjectileShoot2D(hitVec3, hitVec3 + Vector3.down, secondaryItem);
        GlobalWeaponHandler.ProjectileShoot2D(hitVec3, hitVec3 + Vector3.left, secondaryItem);
    }``` For some reason that line is giving me errors in this specific instance. the bullet prefab isn't null in the item scriptable object either
#

the error is a NullReferenceException

lean sail
leaden ice
#

Nvm I see it

#

What Bawsi said

cobalt gyro
#

which debugger though

lean sail
brazen narwhal
#

is someone here familiar with mapbox sdk? how can I add a scalebar to a zoomable map?

red stratus
#

I have the following logic running to calculate required force to move an object an arbitrary speed. I understand speed to be calculated via "s=d/t". I believe thats what I'm doing here. What I dont understand is how it doesnt match up with the rb.velocity.magnitude of the game object. Am I doing something wrong here in the logic?

//update the distance traveled since the last frame
        Vector3 currentPosition = transform.position;
        distanceTraveled += Vector3.Distance(currentPosition, lastPosition);

        //update the time elapsed since the last frame
        timeElapsed += Time.deltaTime;

        //calculate the speed as distance/time
        speed = distanceTraveled / timeElapsed;

        //update the last position variable to the current position for the next frame
        lastPosition = currentPosition;

        //if the current speed is less than the target speed, increase force applied to gameobject
        if (speed < moveScript.targetSpeed)
        {
            moveScript.IncreaseForceFactor(2);
        }
        else
        {
            Debug.Log($"Required force to move {moveScript.gameObject.name} at a target of {moveScript.targetSpeed}, you need a force factor of {moveScript.forceFactor}");
            gameObject.GetComponent<CalculateCurrentSpeed>().enabled = false;
        }
steady moat
slate bramble
#

needs to elaborate a bit on what you expect and what you get instead. Also, how are you applying force, just a single impulse or a continuous force? Remember that velocity = force * time

strong ravine
#

okay, I need help doing a little thing

#

I need the currentActiveSkill property, to keep the value of the class BasicMelleAttack I puted inside.
At the current momment it works some what, i can save values inside this class that is inside the scriptableObject, but at the momment I hit play, or get out of the unity, the property resets, anyone knows a way to solve this?

steady moat
#

Do not use SO to save data.

#

Use real save system.

strong ravine
#

it's not a save function, it's a skill builder

#

I just want it to save the specific skill that I want it to use

slate bramble
#

If you want to persist values between runs of game, you're going to have to use a saving system like writing them to a file etc.

strong ravine
#

this SO saves a class deppending of the specific type of skill that I want to edit on that scriptable objec

#

t

steady moat
#

SO does not save in Runtime.

#

Period.

slate bramble
#

if you want it to have it a specific value at the start of a run just change it in the inspector?

strong ravine
#

i'm not trying to save a change that I made on runtime, i want it to save a change I have edited before starting the game

steady moat
#

Then why are showing melee attack...

#

Show use the code that is creating the SO.

#

!code

tawny elkBOT
#
Posting code

๐Ÿ“ƒ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

๐Ÿ“ƒ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

slate bramble
#

I don't quite get it, if you change it in editor, that should be what it starts out when you run it, unless something else changes it of course

strong ravine
#

okay, gonna try resume the full code

steady moat
#

Or unless you do not correct save the value

red stratus
strong ravine
steady moat
#

EditorUtility.SetDirty();

strong ravine
#

ignore the Byte property, this was me getting desperate

red stratus
steady moat
#

ForceMode.Force: Interprets the input as force (measured in Newtons), and changes the velocity by the value of force * DT / mass. The effect depends on the simulation step length and the mass of the body.

ForceMode.Acceleration: Interprets the parameter as acceleration (measured in meters per second squared), and changes the velocity by the value of force * DT. The effect depends on the simulation step length but doesn't depend on the mass of the body.

ForceMode.Impulse: Interprets the parameter as an impulse (measured in Newtons per second), and changes the velocity by the value of force / mass. The effect depends on the mass of the body but doesn't depend on the simulation step length.

ForceMode.VelocityChange: Interprets the parameter as a direct velocity change (measured in meters per second), and changes the velocity by the value of force. The effect doesn't depend on the mass of the body or the simulation step length.

red stratus
steady moat
#

If you want to apply a force overtime, you gotta apply it overtime

strong ravine
#

Ok, gonna try to explain the things,

I have a scriptable object called ActiveSkillMaker, I want to use this scriptableObject to create every single skill I want, by accessing diferent classes depending of the type of skill and them using UnityEditor to edit the values

the active skill maker has some parameters that every single skill will have, but also has a ActiveSkill_Abstract property, this is the class tha has diferent properties and fuctions deppending of the skill that get put in there.

On the editor, there is a enum that you use to choose a specific type of skill you want to edit, once you choose one, the respective class responsible for that skill is putted on the currentActiveSkill, and you can edit it

#

it works, somewhat, I can edit everything, it works fine and dandy, but at the momment i click start, close the unity editor or anthing that counts as activating the OnDisable(), the currentActiveSkill return to null

steady moat
#

However, if you do neither, your change are not going to be saved.

strong ravine
steady moat
#

You gotta use AssetDatabase.SaveAssets(); I think as well

#

Or manually save

strong ravine
#

also, please look at the link with the full class and other classes afecting the object, it might give a better Idea of what I'm doing. https://hatebin.com/kduqoszguo

steady moat
red stratus
# steady moat No, every force is directly converted in velocity

If this is the case, then impulse is probably what I need to continue with since i'm increasing the force applied by 2 each frame. After removing friction and continuing using the forcemode.impluse, the result is still not matching with the speed calculated by the rigid body. My expected result is the speed value in the Calculate Current Speed script to match the speed value of the rigid body of the object.

steady moat
#

Did you try use an increment of velocity instead of add force

#

If it does not match, then your code is most likely wrong

strong ravine
steady moat
#

I've use Unity Physics to predict and calculate shot, it is pretty accurate. (Not academic accurate, but enough)

red stratus
steady moat
#

Isolate the issue.

#

Reduce the paramters

#

This will lead to something working

#

Then take it from there

#

It is way easier to proceed from working code then non working one.

red stratus
# steady moat It is way easier to proceed from working code then non working one.

Assuming the rigidbody.velocity.magnitude is correct, I can safely assume my issue exists in my CalculateCurrentSpeed script. I'm not sure how to reduce the parameters anymore than it currently is. I get distance and time, then calculate the speed. I've removed friction and updated the code to execute on a fixed time using Time.fixedDeltaTime and using FixedUpdate.

steady moat
#

You also have 2 scripts

hidden flicker
#

how do i make a method accept an argument?

steady moat
red stratus
# steady moat You literally need only 3 things. There is way more than that. - Set the velocit...

I think I have been confusing myself with my understanding of how forces work. If I continuously apply a larger and larger force which is what my script does to reach a target speed, that isnt going to tell me what i'm been looking for with accruacy. That will only tell me the amount of force I was applying at the time of reaching the target speed. I think what I'm actually trying to accomplish is figure out the amount of force to be applied once to instantly reach the target speed.

hidden flicker
#

could i actually get an answer on that?

rigid island
fathom plank
steady moat
hidden flicker
#

shit lmao i forgot the type part

#

i just wrote the parameter without specifying

#

i learned this i just forgot, thank you

fathom plank
#

that would work if you were coding in javascript, but gotta be more specific with types in c#

steady moat
# red stratus I think I have been confusing myself with my understanding of how forces work. I...

No idea what you want, however here is my code that solve the velocity required to make a shot:

    private void SolveForVelocity(Vector3 startPosition, Vector3 endPosition, float gravity, float angle, out Vector3 velocity)
    {
        //x = v * t

        //x = v * cos(a) * t
        //h = v * sin(a) * t + 1 / 2 * g * t ^ 2

        //t = x / (cos(a) * v)
        //h = v * sin(a) * (x / (cos(a) * v)) + 1 / 2 * g * (x / (cos(a) * v)) ^ 2
        //h = v * sin(a) * (x / (cos(a) * v)) + 1 / 2 * g * (x / (cos(a) * v)) * (x / (cos(a) * v))
        //h = v * sin(a) * (x / (cos(a) * v)) + 1 / 2 * g * x ^ 2 / (cos(a) ^ 2 * v ^ 2)
        //h = sin(a) * (x / cos(a)) + 1 / 2 * g * x ^ 2 / (cos(a) ^ 2 * v ^ 2)
        //h - sin(a) * (x / cos(a)) = 1 / 2 * g * x ^ 2 / (cos(a) ^ 2 * v ^ 2)
        //1 / 2 * g * x ^ 2 / (h - sin(a) * (x / cos(a))) = cos(a) ^ 2 * v ^ 2
        //1 / 2 * g * x ^ 2 / (h - sin(a) * (x / cos(a))) / cos(a) ^ 2 = v ^ 2

        Vector3 delta = endPosition - startPosition;

        float x = Mathf.Sqrt(delta.x * delta.x + delta.z * delta.z);
        float x2 = x * x;
        float h = delta.y;
        float g = gravity;
        float sin = Mathf.Sin(Mathf.Deg2Rad * angle);
        float sin2 = sin * sin;
        float cos = Mathf.Cos(Mathf.Deg2Rad * angle);
        float cos2 = cos * cos;

        float r = Mathf.Sqrt((0.5f * g * x2) / (h * cos2 - sin * x * cos));

        Vector2 planeDirection = new Vector3(Mathf.Cos(Mathf.Deg2Rad * angle), Mathf.Sin(Mathf.Deg2Rad * angle));
        Vector3 direction = new Vector3(delta.x, 0, delta.z).normalized * planeDirection.x + Vector3.up * planeDirection.y;
        velocity = direction * r;
    }
#

The velocity is correct and land directly on the target

#
    private void UpdateForVelocity()
    {
        SolveForVelocity(origin.position, target.position, Physics.gravity.y, angle, out Vector3 velocity);

        Vector3 direction = new Vector3(target.position.x, 0, target.position.z) - new Vector3(origin.position.x, 0, origin.position.z);
        this.transform.rotation = Quaternion.LookRotation(direction, Vector3.up) * Quaternion.AngleAxis(angle, Vector3.left);

        if (Input.GetKeyDown(KeyCode.Space))
        {
            GameObject projectile = Instantiate(prefab, origin.position, origin.rotation);
            Rigidbody rigidbody = projectile.GetComponent<Rigidbody>();
            rigidbody.AddForce(velocity, ForceMode.VelocityChange);
        }
    }
red stratus
# steady moat No idea what you want, however here is my code that solve the velocity required ...

What i'm trying to accomplish is figuring out the required amount of force to add to an object using AddForce() to make an object reach a target speed instantly. Though I appreciate the script and your help. I believe I have another route to take to figure out a solution though its more of a brute force than actual programming magic. This script will save me some time later on down the road.

#

Applying an X amount of force only once to reach a target speed of 100 for example

steady moat
#

So, you have an acceleration ?

#

And you want to transform it in velocity ?

#

m/s^2=m/s/s

#

acceleration = velocity / time

#

acceleration * time = velocity

#

Also, I do not understand the fundamental requirement of that.

#

Because, you can simply set the velocity

mossy snow
hidden flicker
#

I want a method to run in void update, but only once triggered, and stop once it reaches a certain point. I can't quite figure out the logistics.

potent sleet
#

!code

tawny elkBOT
#
Posting code

๐Ÿ“ƒ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

๐Ÿ“ƒ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

hidden flicker
red stratus
#

as far as running the method for a duration you can learn about coroutines to take care of it or you can keep track of your time by using Time.deltaTime (time elapsed since your last frame). Everyframe you can update a value that is keeping track of the time between each frame such as the following

float elapsedTime = 0f;
elapsedTime +=Time.DeltaTime;
if(elapsedTime >= duration){
//You will do whatever you need to do to stop once it has reached your target duration
  //do something here.
}

@hidden flicker

#

this is not perfect and you will need to fit it to your code

red stratus
mossy snow
#

F is the amount of force, you need 2 out of the 3 to get the missing one

red stratus
#

by trial and error, i found the mass (100) needed a force of 500000 to acellerate my object to 100

#

yea i know

#

that was my whole question

#

I wasnt sure how to accomplish that lol

#

the force was only going to be applied once

#

accelerate*

#

I guess my question is, how can I programmatically figure out how much force I need to apply to an object once to accelerate it to my target speed instantly.

buoyant crane
red stratus
#

No I need to use AddForce so I cant set the velocity directly

#

so accelerate would be the wrong word I suppose since it would reach the target speed instantly

buoyant crane
lean sail
red stratus
#

At this point I can go in any direction but I want to limit it to AddForce for potential later applications and my own personally learning

buoyant crane
#

Tbh I still donโ€™t really understand why, velocity gives you perfect control over how the object moves.

lavish mason
#

I was trying to make a menu for my game but the input module wasnโ€™t picking up the axis of the left stick

buoyant crane
# red stratus No I need to use AddForce so I cant set the velocity directly

You can use a PID algorithm. Itโ€™ll attempt to add force and decrease it over time as the speed gets closer to the target. The reason why you canโ€™t really calculate it is because Force is mass * acceleration. To instantly (near instantly) move an object to a target speed, you have to add a super high acceleration to speed it up, and then a low one so it doesnโ€™t accelerate faster.

hexed pecan
#

You could add a force that is (targetVelocity - currentVelocity) * someMultiplier

#

If you want to gradually reach targetVelocity, that is

red stratus
#

playing around with it, this seems to have gotten me close but I had to apply a real number duration

public class ForceCalcuator : MonoBehaviour
{
    private Rigidbody body;
    public float targetSpeed = 100f;
    public float accelerationDurationInSeconds = 1;
    private bool onlyOnce = true;
    // Start is called before the first frame update
    void Start()
    {
        body = GetComponent<Rigidbody>();
    }

    private void FixedUpdate()
    {
        if (onlyOnce)
        {
            onlyOnce = false;
            float requiredForce = (body.mass * targetSpeed) / accelerationDurationInSeconds;
            Debug.Log($"Force required {requiredForce}");
            body.AddForce(Vector3.forward * requiredForce, ForceMode.Impulse);
        }
    }
}
buoyant crane
#

A small example with just a P controller (PID but just the Proportional term):

float diff = target speed - current speed
rb.AddForce(diff * 100);```
If the difference is positive and itโ€™ll  add speed in the positive direction, and vice versa. If the distance is small itโ€™ll add a weak force and vice versa. Itโ€™ll have this back and forth feeling of high speed and low speed so you need to tune it correctly
lean sail
#

Is this part really the performance issue of your program? If it's an insanely large list, I would store the average and recalculate it purely based on new entries or removed entries

late lion
#

How big are the lists you're running through this? Or how often are you running the method? It would have to be a pretty big number for it to make a difference in performance.

#

How many lakes on average?

hexed pecan
#

The .Contains might be a bit heavy here

verbal granite
#

Hello, is there a way to make a collider that changes shape over time? Or should I have it destroy and then re-create with the new shape each frame?

hexed pecan
#

Contains is way faster on a HashSet than a list, but then again Add is slower

#

So I cant say for sure

jade phoenix
#
    void Update()
    {
        var gyro = Input.gyro;
        var cameraRot = gameObject.transform.rotation;
        var newRot = Quaternion.Euler(cameraRot.x, cameraRot.y, gyro.attitude.eulerAngles.z);
        gameObject.transform.rotation = newRot;
    }```would anyone know why this code still allows the camera to flip when i rotate my phone on the x axis?
verbal granite
#

Also, if a collider moves from point A to point B the next frame, will it collide with things inbetween point A and point B, even if they collider itself is not in that position on either frame? Hopefully that makes sense

late lion
verbal granite
late lion
#

There's a limit to how optimized you can make the compares. At some point, you need to reduce the number of compares. This could be done by reducing the number of lakes you spawn, or by using a spatial tree, like a quadtree.

hexed pecan
fervent snow
#

hey all. I'm trying to make a canvas to display icons for units in a game. I want to cull icons when off screen. Is there a quick way to check if a vector3 is within the view frustrum?

verbal granite
lean sail
#

you would have problems running anything 5 million times

hexed pecan
verbal granite
hexed pecan
#

Contains will get linearly more expensive relative to amount of items in the list

lean sail
#

you may have to implement some other data structure then, so your methods can have early outs

verbal granite
hexed pecan
#

In that case list is probably faster

#

Linq has Array.Contains but I think its pretty slow

#

Never used

#

Just assuming tbh

lean sail
#

still you could cut out performance time by doing what i said with the list before, storing the average instead of recalculating every single one

hexed pecan
fervent furnace
#

Can you use dfs to flood fill each lake? then get the โ€œcenterโ€ of each lake when running dfs?

jade phoenix
lean sail
#

im sure theres a lot of ways to do it, i would probably have some struct or class for a lake though where you store the x,y and the average is calculated internally

fathom plank
#

list.contains is also typically slower than hashset.contains as well, so if you can conver to that and get away with it, might offer some better performance

quartz folio
late lion
#

@swift falcon Also note that List is not thread safe to write to, so it's not safe to use inside a Parallel.ForEach. You might not be seeing issues now because the Parallel.ForEach might not actually be parallel, but it could be on other computers.

fervent furnace
#

Depth first search

fathom plank
#

profile it ๐Ÿคทโ€โ™‚๏ธ

lean sail
#

how much is a big slowdown, world generation especially for 1 million tiles is gonna always take a little bit of time

#

if you're talking like a minute, just slap a loading bar on that

fervent furnace
#

I will consider using a dfs and get all center of the lakes and do nearest neighbour search find out the lakes close to each other and you can start dfs again to flood fill the lake from its center

late lion
#

You would have to lock every usage of it, because you can't have a thread try to read from it while another thread writes to it at the same time.

#

And a lock will slow things down.

fathom plank
#

depending on what you're generating (like its compexity, etc) you could offload to a compute shader, provided whatever platform you're building for supports it (most do these days)

jade phoenix
#

individual axis are just getters, not setters and you cant add vectors together

hexed pecan
#

Ofc you can add vectors together

#

And you can set an axis

lean sail
#

which is wrong

jade phoenix
#

thats why i turn it into a euler angle first gyro.attitude.eulerAngles.z

lean sail
fathom plank
#

sorry for potato quality video, but if you're just doing simple mesh generation, compute shaders are insanely fast. This video im using marching cubes to generate a big mesh every frame with a noise function at over 500 fps https://i.imgur.com/ZDjXyou.mp4

jade phoenix
#

cameraRot is a quaternion by default

#

cause its rotation no?

#

it says Quaternion

jade phoenix
#

oh wait

#

shoot

#

i made a severe lapse in error

late lion
#

Sure, but concurrent collections have their own performance concerns.

misty cypress
#

https://hatebin.com/yohgdjimfz
So i have code here that is for a 3d unity player for a first person game, the code is for a grabbing mechanism like in the game portal, so basically it consists of a grab range in which how far you can grab an object, a grabbable mask, in which to tell apart which objects you are allowed to grab, and a Hold position (The game object in front of the player which will determine the position of the grabbed object. Where im having trouble with is the part is the Hold position gameobject following the mouse x and y axes like the camera does. Please help I don't know how to do this, Note: There is also an anchor gameobject placed in the same area as the camera (In the head of the player) which acts as the object the Hold position gameobject rotates around. The hold position gameobject is a child of the anchor and the anchor is a child of the player.

late lion
#

You would have to run all the generation on a separate thread.

lean sail
fathom plank
jade phoenix
#

is there even a point of doing this then?cs var newRot = Quaternion.Euler(cameraRot.eulerAngles.x, cameraRot.eulerAngles.y, gyro.attitude.eulerAngles.z);

#

or do i just use all quaternion values and it works the exact same

quartz folio
hexed pecan
quartz folio
#

Only through the helper methods will anything valid happen

fathom plank
#

you could also break each thing down into a chunk and write without locking where each thread writes to its own chunk instead of one big list where you have to lock

fervent furnace
#

@swift falcon do you want to find out all the center of all separated lakes and find out some closes pair then remove one lake of these close pairs?

fathom plank
# hexed pecan Do you use AsyncGPUReadback?

i have, but in this example, im actually also rendering it on the gpu directly from the buffer the compute shader is writing to, so i dont need to read it back, but yeah if you want colliders to work, you'll need to do the read back

jade phoenix
quartz folio
idle harness
#
if(!player.GetComponent<LockOnHandler>().visibleEnemys.Exists(gameObject)) 
{
player.GetComponent<LockOnHandler>().visibleEnemys.Add(this.gameObject);
}

this causes C1053 error: cannot convert "UnityEngine.GameObject" to "System.Predicate<UnityEngine.GameObject>".
What should I do?

fathom plank
#

just dont do any of the generation on the main thread, and only move the data over to the main thread once you've finished generating the chunk or w/e, that will prevent the game from freezing even while the genration is happening

jade phoenix
quartz folio
#

It's totally fine

jade phoenix
#

then im confused about which part of that code snippet i sent which is incorrectly using quaternion members

quartz folio
#

You were reading x and y from a quaternion, cameraRot

fathom plank
#

the TL;DR w/ unity afaik is, unless ur using the dots job system, you can't do anything that interacts with the engine directly outside of the main thread, but a mesh is just a set of data, so you can easily generate that outside of the main thread without needing to use any unity functions, then onces done, you can convert it to a unity style mesh on the main thread

jade phoenix
#

i was reading from cameraRot.eulerAngles.x/y/z

jade phoenix
#

oh mb i had changed it since then

fathom plank
#

just google multi threading tutorials for c# it works the same

jade phoenix
quartz folio
#

Yes, though it may or may not do what you expect depending on the values of the euler angles because euler angles are truly an annoying system of compound rotations performed in a specific order (Z, X, Y)

jade phoenix
#

i really just want to disregard every axis except for tilting the phone on the z axis. if theres a better way, i'd love to hear it as my current experience with the way i've been doing it has been really rough

pure cliff
#

I have a class (Gamestate) implementing an event (PropertyChanged), that invocation of it is not publicly exposed (it gets triggered via unexposed logic internally.

However, I want the ability to open a "transaction" that will not invoke the event until the transaction is finalized, as an IDisposable sort of deal, with a filter.

Something like:

using var transaction = GameState.OpenTransaction(g => g.UI);
GameState.UI.Blah = whatever; // << This would normally trigger the event, but it wont inside the transaction asap
GameState.UI.Foo = something;
GameState.UI.Bar = somethingElse;
transaction.Commit(); // This will cause a *single* event to now fire off, rather than multiple

I want the transaction.Commit() to trigger the event which is on GameState, however, I dont want the method to trigger the event to exposed to anything else. Right now its private.

Thoughts?

jade phoenix
vernal bridge
#

hello people of this server

#

im not sure if this is the right channel

#

but

#

i cant jump in my 2d game on unity

#
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    private float horizontal;
    private float speed = 8f;
    private float jumpingPower = 16f;
    private bool isFacingRight = true;

    [SerializeField] private Rigidbody2D rb;
    [SerializeField] private Transform groundCheck;
    [SerializeField] private LayerMask groundLayer;

    void Update()
    {
        horizontal = Input.GetAxisRaw("Horizontal");

        if (Input.GetButtonDown("Jump") && IsGrounded())
        {
            rb.velocity = new Vector2(rb.velocity.x, jumpingPower);
        }

        if (Input.GetButtonUp("Jump") && rb.velocity.y > 0f)
        {
            rb.velocity = new Vector2(rb.velocity.x, rb.velocity.y * 0.5f);
        }

        Flip();
    }

    private void FixedUpdate()
    {
        rb.velocity = new Vector2(horizontal * speed, rb.velocity.y);
    }

    private bool IsGrounded()
    {
        return Physics2D.OverlapCircle(groundCheck.position, 0.2f, groundLayer);
    }

    private void Flip()
    {
        if (isFacingRight && horizontal < 0f || !isFacingRight && horizontal > 0f)
        {
            isFacingRight = !isFacingRight;
            Vector3 localScale = transform.localScale;
            localScale.x *= -1f;
            transform.localScale = localScale;
        }
    }
}```
steady moat
red stratus
vernal bridge
vernal bridge
pure cliff
#

I should now be able to simply open a txn like so, I think:

using var txn = GameState.OpenTransaction();
GameState.Something = something else // wont fire event just yet
GameState.Foo = bar;
GameState.Phi = baz;
txn.Commit(); // Now the events will fire, and only distinct ones in case of overlaps;
hidden compass
#

im looking through old repo's currently, trying to see if i can't find it

vernal bridge
#

i set up my input button it still displays this error

ArgumentException: Input Button space is not setup.
To change the input settings use: Edit -> Settings -> Input
UnityEngine.Input.GetButtonDown (System.String buttonName) (at <dbc9087e67094ae597a416f542bc9023>:0)
PlayerMovement.Update () (at Assets/PlayerMovement.cs:37)

small trench
vernal bridge
#

i just tried it now

#

i get another error

small trench
#

And what is it?

vernal bridge
#

ArgumentNullException: Value cannot be null.
Parameter name: source
UnityEngine.AudioSource.Play () (at <ffe857c3421441dd831fcce832acbe2a>:0)
PlayerMovement.Update () (at Assets/PlayerMovement.cs:39)

small trench
#

Well you haven't assigned the audio source have you

vernal bridge
#

?

#

hmm

#

how do i

#

i havent done anything related to audio in my project

small trench
#

You haven't assigned the audio source into the inspector or referenced it using GetComponent

small trench
rain minnow
#

What is on line 39 in PlayerMovement?

small trench
vernal bridge
rain minnow
#

Doesn't matter, show us the error code . . .

vernal bridge
#

let me check

rain minnow
#

Are we pointing fingers or trying to solve a problem?

vernal bridge
#

{
dirX = Input.GetAxisRaw("Horizontal");
rb.velocity = new Vector2(dirX * moveSpeed, rb.velocity.y);

    if (Input.GetKeyDown(KeyCode.Space) && IsGrounded())
    {
        jumpSoundEffect.Play();
        rb.velocity = new Vector2(rb.velocity.x, jumpForce);
    }

    UpdateAnimationState();
}
#

34-44

#

liines 34-44

#

jumpSoundEffect.Play();

tawny elkBOT
#
Posting code

๐Ÿ“ƒ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

๐Ÿ“ƒ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

rain minnow
#

Not easily readable. Which is line 39? That's the error line . . .

vernal bridge
#

jumpSoundEffect.Play();

#

is line 39

rain minnow
#

Then check if any reference variable on that line is null . . .

#

This becomes easy as there is only one variable on that line . . .

keen obsidian
#

question about spawning using coroutines

rain minnow
#

Check that jumpSoundEffect is assigned and not null . . .

gloomy stirrup
#

In my game. I am gonna use a auto aim feature when user so that clicks the fire button (on mobile) it fires in the direction of the enemy automatically... I have made characters with all four sides attack animations... is it possible to play the correct animation according to direction in which the user aimed and attacked by pressing the button ???

rancid stream
#

Hey, using C# delegates for events currently, should I be using UnityEvents instead? Is there any resources for how to do so?
Running into issues with re-loading scenes not resulting in a proper reset, but there's probably many other solutions to this.

public delegate void EInt(int value);
public static EInt OnNewScore;
// sub/unsub in some GameObject's OnEnable/OnDisable
lean sail
#

just stating as well, the code you've shown isnt an event at all, its just a delegate. An event is specific where you cant invoke its logic outside the class, only the add/remove listener functions are exposed

rancid stream
cosmic rain
#

Sounds like x y problem

#

Maybe actually share info on your issue.

ashen yoke
#

reloading scene not reseting, do you have domain reload on play disabled?

#

or you mean reloading in editor, opening another scene?

#

the only way the statics are cleared is on domain reload

#

otherwise you have to use [RuntimeInitializeOnLoadMethod] for runtime and InitializeOnLoadMethod for editor

rancid stream
#

Sorry I was wrestling some Plastic issues lol

rancid stream
ashen yoke
#

use the attributes to reset statics then

#

better read the doc page for domain reload

rancid stream
#

So I have two kinds of bindings: one to an in-scene Player class' public methods. Those work OK.
The second to a singelton manager, that works the first time. On scene reload, it stops working though.

ashen yoke
#

its all there

gloomy stirrup
rancid stream
ashen yoke
#

runtime?

rancid stream
#

Yeah at runtime

lean sail
ashen yoke
#

that sounds like a bad design, because it means you would have to handle clearing statics yourself when you switch scenes

gloomy stirrup
ashen yoke
cosmic rain
ashen yoke
#

if its just a singleton the problem is in the code of your singleton instance getter

#

show it

rancid stream
#

I don't 100% think the input binding goes to the Instance though

    public static GameManager Instance { get; private set; }

    void OnEnable()
    {
        if (Instance == null) { Instance = this; }
        else { Destroy(gameObject); }
    }
ashen yoke
gloomy stirrup
rancid stream
# ashen yoke just the button doesnt work?

Sorry brainfart, the escape button (to bring up the pause menu) stops working. Previous issue was that it would come up but the reset button wouldn't work, but I broke it further lol

ashen yoke
#

looks like spaghetti, input manager which should not know of any of the consumers of input is somehow PlayerInput at the same time as InputManager, and stores a reference to GameManager

rancid stream
#

I think I just followed the Unity quick start guide, I guess if I bind in OnEnable it might continue working?

cosmic rain
# gloomy stirrup 2D, a top down game have animation for four side movement, up down left right, l...

Ok, well, your auto aim should only be responsible for getting the direction to the target. Animating the character should be handled by the character controller. For example:

  • Button pressed
  • Character controller gets the direction from the auto aim
  • Character controller checks if the character is facing in the right direction and changes animation if needed.
  • Character controller start the shooting logic.
    etc...
ashen yoke
#

i cant deduct your scene structure from that

#

im trying to understand - the PlayerInput should dictate which method is being called when input happens?

#

thats the idea?

gloomy stirrup
ashen yoke
#

are all the unity events referencing objects in the same scene and are present at edit time?

rancid stream
ashen yoke
#

where is this InputManager located?

rancid stream
rancid stream
ashen yoke
#

do you know which variable becomes null on scene load?

rancid stream
#

I don't think it's a null reference issue? It's just that the Toggle Pause action doesn't call the relevant method any more

ashen yoke
#

ok, are you enabling/disabling the action map?

rancid stream
#

Nope, it continues working (mostly) because I can still fire and aim after the reload.

ashen yoke
#

so the problem is specific to toggle pause

#

show the method that handles it

rancid stream
#

Yeah, I'm guessing something to do with the singleton-ness

ashen yoke
#

do you see the event in the inspector after load?

rancid stream
ashen yoke
#

thats not TogglePause

rancid stream
#

Uhh sorry haha
But no

#

It clears out after re-load

ashen yoke
#

others dont?

rancid stream
#

Yeah the others stay bound

cosmic rain
#

Must be referencing an object that gets destroyed.๐Ÿคทโ€โ™‚๏ธ

ashen yoke
#

is Managers in DDOL?

rancid stream
# ashen yoke thats not TogglePause
    public void TogglePause()
    {
        Debug.Log($"TogglePause called with {IsPaused}");
        IsPaused = !IsPaused;
        SetPausedState(IsPaused);
    }

    void SetPausedState(bool pauseState)
    {
        if (pauseState)
        {
            Time.timeScale = 0;
            AudioListener.pause = true;
            Events.OnPaused?.Invoke();
        }
        else
        {
            Time.timeScale = 1;
            AudioListener.pause = false;
            Events.OnResumed?.Invoke();
        }
    }
rancid stream
cosmic rain
ashen yoke
#

my guess is, the scene has a reference to manager serialized in the event

#

new scene is loaded, your singleton still sees the value in static field

#

destroys the newly loaded manager

ashen yoke
#

the reference is invalid as a result

#

in your case you are misusing static backing field

#

typically the intent is to keep a single instance in it over the lifetime of the game

#

but it wont work with your setup

#

because you are serializing references to specific instances

cosmic rain
#

The simplest solution would be to call a method on the same object. Something like OnTogglePausePressed in an InputHandler component or something. That would do something like GameManager.TogglePause().

ashen yoke
#

or to invert it and hook events dynamically from the observer

rancid stream
scarlet rover
#

When you write

Debug.Log($"TogglePause called with {IsPaused}");

what is the difference between that and

Debug.Log("Toggle Pause called with "  + isPaused);
ashen yoke
#
class GameManager
{
    void OnEnabled()
    {
      InputManager.Instance.onPause += HandlePause;
    }

    void OnDisable()
    {
      InputManager.Instance.onPause -= HandlePause;
    }
}
ashen yoke
#

second is string concatenation

#

google interpolated strings

#

google all 3 things

scarlet rover
#

Ya I did and it says that it will evaluate the variable that is in curly q's

#

does the second not do that?

ashen yoke
#

second does ToString() same way first one does, with one difference, no format, and each + will allocate a new string

#

you are chaining string.join

rancid stream
ashen yoke
#

PlayerInput in your case

rancid stream
#

Hmm it's all setup in the GUI for now, might need to change that

scarlet rover
#

oh so for the example that I used, if you wanted to add more variables in, its less writing at least...I could in theory do $"This {var1}{var2}{var3}{var4}" where in concat I have to "This" + var1 + var2 + var3 + var4

#

and even then it wouldnt look pretty because I dont have spaces

#

I would need $ before it though

rancid stream
cosmic rain
scarlet rover
#

ya I hear you! Thanks...I ask some questions but enjoy reading the posts as well to learn so just follow up off other users as well

sinful marsh
#

gotta be self aware

gray mural
#

but that's more readable

sinful marsh
#

yeah it's just for readability

rancid stream
# ashen yoke PlayerInput in your case

Thanks so much for all the help! I ended up moving to SendMessages instead, and adding small functions to invoke the events desired instead. Seems solid so far, cheers!

ashen yoke
rancid stream
ashen yoke
#

syntactic sugar is when compiler compiles code into something else

ashen yoke
#

SendMessages is runtime construct, resolved at runtime, using reflection or whatever unity does

#

yes there is a better option, rethink your architecture so that observers can find the observables

woeful tapir
#

do u know what this error is ?

ashen yoke
#

reset layout see if it fixes it

woeful tapir
woeful tapir
#

i still got it

quartz folio
woeful tapir
#

like close and open again right ?

#

thanks a lot

#

it works

gloomy stirrup
#

How Do I get the direction of enemy to update this parameters... I am using auto aim... the nearest enemy will get hit by the Player when user clicks button (on Mobile)... but then to play the respective animation how will I get the direction of the enemy... I have four attack animation for all four direction ( as we do in 2D movement animation)

#

I want that when enemy is upward the vertical_attacking float should be -1, when its Up vertical_attacking float should become +1 .. same for the left and right

#

so that the correction animation play on correct time