#πŸ’»β”ƒcode-beginner

1 messages Β· Page 574 of 1

naive pawn
#

you shouldn't use return

#

you should use an else there

tough plinth
#

I thought like unity would just skip that block if it's not true, so it will move to the next

naive pawn
#

you mightve had an else if block instead of an if

tough plinth
#

Why didn't it work?

naive pawn
#

also, fyi, you can check backCamEnabled or !backCamEnabled directly instead of comparing it to booleans
or alternatively, you could just not use a conditional at all

backCamEnabled = !backCamEnabled;
backViewCamera.SetActive(backCamEnabled);
frontViewCamera.SetActive(!backCamEnabled);
naive pawn
#

if backCamEnabled starts out true, then the first conditional is checked, backCamEnabled is set to false, then the second conditional is checked so it's set back to true

with an else if instead of the if in the second conditional, the second conditional is only checked if the first one is false

tough plinth
naive pawn
#

i think you're misdiagnosing the problem
the first if works as intended; the problem is in the second if, which reverts the first one

tough plinth
#

Yeah, changing it to else fixed the problem

naive pawn
tough plinth
#

And also, why return was a bad idea?

naive pawn
#

it's not bad in general; but this is in Update, it's not unlikely to want to add more behavior in the future
if you use return here for an early exit, that just sets up problems for the future

#

setting up the proper logic flow keeps the "skip" contained to the "camera flip" logic instead of affecting the entire Update cycle

tough plinth
#

So, to not break the game and code in the future, using return is a meh idea

naive pawn
#

in this situation, yes

burnt vapor
#

When your if-statement is entered, backCamEnabled is set to false. After that, the next if-statement is called. Note that the two are not related so it's not going to skip it in any way. In this case since you set it to false it will now also call this statement since you changed it.

You should not use return; here inside the if-statement. That is very confusing. Instead, considering there are two flows here, you use else. Even better would be to separate the two methods into their own method since it now does two different things. You should not put too much login in an Update method anyway.

naive pawn
#

i would not recommend separating this into more methods

naive pawn
burnt vapor
#

That's not a good idea. If code needs to explicitly disable it then that feature no longer exists

#

So, make two separate methods for code to call, and then just call one or the other depending on backCamEnabled. If you make it a toggle there's no way to call individual methods unless you add yet more checks against backCamEnabled

#

You could make a third method, which toggles this. It would check backCamEnabled and call one of the methods based on its state

naive pawn
#

i have no idea what you're talking about at this point

#

that feature no longer exists
what feature?

burnt vapor
#

The ability to explicitly disable the backCam using code that doesn't use a toggle

naive pawn
#

im so confused what you're talking about

burnt vapor
#

This code is a toggle, but what if you have code that just required it to be disabled? That doesn't work

#

I don't know how else to explain

languid spire
naive pawn
#

why wouldn't that work with a toggle?

burnt vapor
#

We're talking about two camera's here. The fact that it's on a gameobject is irellevant

naive pawn
#

ok, code that requires a camera to be disabled?

burnt vapor
#

I don't know how much clearer I can be. You're making a method that serves as a toggle when you should just keep the two behaviours separated

naive pawn
#

what 2 behaviors? enabling camera A vs enabling camera B?

burnt vapor
#

Yes

naive pawn
#

that's just silly

#

it is a toggle

#

because you're switching between 2 cameras being exclusively active

languid spire
naive pawn
#

that is toggling between camera A and camera B

burnt vapor
#

So what if they have code that requires the back camera to be active, even thought it might already be active?

#

You only have a toggle, there's no way to make sure it's active now. If you use the toggle, you just turn the other one active

#

You now have to add explicit checks to ensure it's not already active when you could have just had it as a separate method that enables it, which ignores the call since it already is enabled

burnt vapor
#

At the very least you should make it a method that updates its state the same way as made [here](#πŸ’»β”ƒcode-beginner message), but backCamEnabled is not toggled but rather set through one of the two methods.

languid spire
burnt vapor
#

A professional dev would know how to write code so it's not introducing possible limitations in the future. I'd argue it's very much the case here

#

A CS student would do the exact opposite

languid spire
#

no, students want everything to conform to the nice patterns and principles they have learned. Professionals write code to fit the design they are working with, not what 'may be'

astral falcon
#

Did the comments help you @tough plinth ? Or are you still left without a solution yet

naive pawn
tough plinth
naive pawn
#

tip: use a single backtick on either side to get inline code

#

ah

#

lmao

tough plinth
#

Yeah, I kinda messed with them

naive pawn
#

if it's just else, there's no condition to check, it just runs the second block if the first condition was false

tough plinth
#

Like I said, alternative way, and if Else If it will check it

naive pawn
#

technically, there's no else if in c# (same for some other languages), it's just an else followed by an if
you can reformat an if-else tree to see the equivalence

if (a) A();
else if (b) B();
else C();
// equivalent to
if (a) A();
else {
  if (b) B();
  else C();
}
tough plinth
#

So there is no much difference between them and you should use Else If or Else depending what you want?

naive pawn
tough plinth
#

ah

naive pawn
tough plinth
#

I will think of else like a lazy way to make something xD

astral falcon
#

Else usually isbeing used if you return logs for example. check if something is met, if not, log your output. I personally never use else if, because this is like the headstart to run iinto a big else if mess, which you might wanna avoid in the first place anyways πŸ˜„

#

If possible, I then jump over to a switch case

tough plinth
#

(Connectors like Else and Else If)

naive pawn
#

"exclusive" means only 1 will run

astral falcon
#

The first, that is met on the else if chain will run

tough plinth
naive pawn
#

compare these 2 scenarios:

if (a) A();
if (b) B();
```vs```cs
if (a) A();
else if (b) B();
```in the former case, those are 2 separate conditionals
if `a` and `b` are both true, both `A` and `B` will run
in the latter case, those are chained together. only if `a` is false, then the `else` will be reached, then `b` will be checked. so if `a` and `b` are both true, only `A` will run

the former would have `A` and `B` be non-exclusive, while the latter would have them be exclusive
burnt vapor
#

The fact that it supports what "may be" is a side effect to just sticking to the old approach. I just suggested it were placed in two separate methods so the if-else is an additional indentation in the code, and it's reusable.

#

This by itself was also more a suggestion since putting everything in an Update method makes it unreadable

tough plinth
naive pawn
#

which one are you referring to?

tough plinth
#

My script that I used

naive pawn
#

the original one?

tough plinth
#

Yeah

naive pawn
#

no in your original, both are running

#

because b is checked after a

#

in your case, a (backCamEnabled == true) is initially true, so that block runs
inside A, you do backCamEnabled = false
then the second if is reached: now b is true, so B also runs

tough plinth
astral falcon
# tough plinth My script that I used

You might let the illusion go, that the if statements are magically connected if there is more than one. Could that be the case? If you have two if statements just below each other, they act completely independently

naive pawn
tough plinth
#

Sorry for being unclear

naive pawn
#

the second block does work there

#

it is checked

tough plinth
#

Then, why it didn't work?

#

I'm confused D:

naive pawn
#

it does "work"

#

it just doesn't work correctly for your task

astral falcon
#

You say, is backcam enabled, then disable and then you say, is it disabled (which it is) reenable it

burnt vapor
#

It works, but your first if-block sets backCamEnabled to false. After that the second if-block is being checked, and it sees that it's false

#

It's not skipped. If you want it to be skipped you have to use an else if

#

Right now it's two checks that get checked individually

hot laurel
#

at this point just use switchπŸ˜†

burnt vapor
#

Not at all

tough plinth
astral falcon
#

I still would just go for this πŸ˜„

backViewCamera.SetActive(!backViewCamera.activeSelf);
frontViewCamera.SetActive(!backViewCamera.activeSelf);
burnt vapor
#

Sure, but they should definitely understand why the flow here has to be changed in general

naive pawn
astral falcon
burnt vapor
#

If they deliberately skip eachother then that would be weird

tough plinth
astral falcon
#

can I suggest you take a break? πŸ˜„

naive pawn
#

yeah lua doesn't do that

burnt vapor
#

Lua has elseif

tough plinth
burnt vapor
#

So even there it's not like that

#

The only difference is a space πŸ˜›

astral falcon
#

Just take a break and a deep breath, things will get clearer on their own

naive pawn
#

in lua, if you put an if after another if, without an end, then the second one would be inside the first
but that's not the same as if/else if

tough plinth
#

So, in Unity If and If are independent, and they do their own thing. And to make a connection between them and make sure they interact with each other, Else or Else If should be used

naive pawn
#

like something like this

if true then print(0)
if true then print(1)
end end
```would be properly formatted as this
```lua
if true then
  print(0)
  if true then
    print(1)
  end
end
naive pawn
burnt vapor
#

In your case, the issue is that it can enter the first if-block, but after that it can also enter the other one due to the missing else in else if

#

You could even just make it an else. Your boolean check will always be false regardless since you already checked for true

visual linden
#

The way you guys always manage to spin the simplest question into a full blown philosophical discussion will never cease to amaze me πŸ˜…

burnt vapor
#

So true

#

Should have honestly just linked docs about if-statements

naive pawn
#

a full blown philosophical discussion?
there were at least 2 here

burnt vapor
visual linden
#

You weren't expecting a pop quiz there, were you

tough plinth
#

So it enters 1st block and then instantly goes to 2nd, because it's not connected, so it's get messy

burnt vapor
#

Pretty much

tough plinth
#

Omgmgkbhjjg

burnt vapor
#

They have no connection in any way

#

They are both individual checks

#

If you want to invoke on of the other, use an if-else

#

If you want to invoke one, or conditionally invoke another one if that one doesn't pass, use if followed by else if

#

You can chain else if statements infinitely

#
if(...)
{
}
else if(...)
{
}
else if(...)
{
}
else if(...)
{
}
...
#

If one matches the predicate you added, it will invoke and break the chain

#

The very last statement in a chain can also just be else, in which case it will always be invoked if nothing else up the chain invoked

#

You know these things are very well explained online. I'm confused why people are trying to explain this in general considering it will never be as detailed

tough plinth
#

So they are just not connected with each other, so the full logic does not work, however unity successful goes through this code.

Even if 1st code is totally right, 2nd block cannot be called because it's not connected with Else or Else-if

burnt vapor
#

The logic does work, just not what you expected

#

Both if-statements are invoked

tough plinth
#

Ye

astral falcon
#

Running in circles πŸ˜„

burnt vapor
#

The confusing part is that the first one changes the boolean again

#

So somehow it invokes the second one

tough plinth
#

I used Debug.Log and it was stuck with True, so I understand why

naive pawn
#

2nd block is called

#

that's the entire problem

burnt vapor
#

Please just read the documentation of if statements

#

And change the second block to an else if, see what it changes

naive pawn
#

i think you initially misdiagnosed the problem and you've internalized it

tough plinth
#

"Beginner programming" they said atwhatcost

naive pawn
#

the 2nd block is called, that's where the true comes from

burnt vapor
#

An if-statement is the most beginner thing that exists

naive pawn
burnt vapor
#

No arguments in the chat

burnt vapor
#

But I think this idea of Lua doing it differently made you assume it works differently

#

... even though Lua works the same

astral falcon
#

oh boy πŸ˜„ I think, the question was answered and windy can read on it on his/her own and test around to understand.

burnt vapor
#

Are you sure? Maybe we need to explain it again just to make sure.

tough plinth
#

Well, with help of this chat I think I learned the lesson UnityChanPanicWork

burnt vapor
#

Which is?

#

Read the docs?

tough plinth
#

of uninstalling Lua from my pc

burnt vapor
#

That's a good conclusion to take

tough plinth
#

I will take a look at the docs to figure it out, if anything, I will just re-read entire conversation, so yeahUnityChanThumbsUp

burnt vapor
#

Feel free to ask more questions on the code so we can yet another argument in here about what's best πŸ˜“

tough plinth
#

Anyways, Thanks for the help!!! ❀️@burnt vapor , @astral falcon , @naive pawn, @visual linden UnityChanCelebrate

final kestrel
#

!code

eternal falconBOT
naive pawn
final kestrel
#

Hey all. I followed a tutorial for my first person controller. https://hastebin.skyra.pw/ubeyasetur.csharp and this is where I handle my movements. However when I do force my player to look target https://hastebin.skyra.pw/fiwefoxemo.csharp as in here, after it succesfully looks at target, it automatically snaps back to where my mouse position was when I get into the trigger. Can someone point me to the right direction of what to do please?

#

Also I have this same problem when I interact with my doors, which basically just teleports the player from one location to another. Then it immediately snaps my mouse position to where I was looking at when I interacted with the door.

visual linden
#

You are rotating the camera but your player controller rotates the character controller transform, hence the actual look direction isn't changing when you forcibly rotate your camera.

final kestrel
#

So what you are saying is that I also have to rotate my character controller?

#

I mean the transform of my player.

visual linden
#
    private void HandleMouseLook()
    {
        rotationX -= Input.GetAxis("Mouse Y") * lookSpeedY;
        rotationX = Mathf.Clamp(rotationX, -upperLookLimit, lowerLookLimit);
        _cameraRoot.transform.localRotation = Quaternion.Euler(rotationX, 0, 0);
        transform.rotation *= Quaternion.Euler(0, Input.GetAxis("Mouse X") * lookSpeedX, 0);
    }```
Yeah, you can look at how your player controller is doing the mouse look.
final kestrel
#

Right. Up and down mouse movement affects cameraRoot transform while left and right affects my player transform.

#

Will I have to store where my lookTarget is positioned? And set my camera and player's rotation accordingly?

#

Or will it pick up after I enable canMove and canMouseLook

#

Thanks for the help btw it was super helpful!

cerulean badger
#

How do I insert a hexadecimal value to a color component? Idk how's the syntax here in unity

naive pawn
#

in the inspector?

#

or through code?

cerulean badger
#

in the script

naive pawn
#

what component are you talking about here exactly?

cerulean badger
#

I want to change the color from global light 2d

naive pawn
#

there's no component named Color

#

ah

cerulean badger
#

GameObject.Find("Global Light 2D").GetComponent<Light2D>().Color = 8C0000;

#

i put it this way

rich ice
#

just convert it to RGB first

naive pawn
#

8C0000 isn't valid c#

#

also Color isn't a valid property

#

a Light2D has a color

rich ice
naive pawn
#

you don't need to do this

rich ice
#

wait you can?

#

i've never had to conveert a hex to RBG before, with c#. i normally just get the RGB values and use those

naive pawn
#

Color takes floats from 0 to 1, not ints from 0 to 255

#

you'd assign the .color to, for example, new(0x8C/255f, 0x00/255f, 0x00/255f)
you can use the hex values directly like that

naive pawn
#

it's just a way to interpret some other value, like a string or an integer

#

if you wanted an rgb integer, you could just do 0x8C0000, for example

cerulean badger
#

so how would I write this in the code?

#

I got a bit confused

rich ice
naive pawn
naive pawn
#

you could also use floats directly, new(0.55f, 0f, 0f)

#

you could also write the constructor in full, new Color(...)

rich ice
#

(example image is a bit messy, i just shoved this into another script with a bunch of other stuff guh )

naive pawn
#

mmm yes i think im looking at the wrong docs

burnt vapor
#

Just put a # before it or it will not be valid

astral falcon
naive pawn
#

oh yeah, i keep forgetting that exists

cerulean badger
#

GameObject.Find("Global Light 2D").GetComponent<Light2D>().Color = new(0x8C/255f, 0x00/255f, 0x00/255f);

#

is this correct?

astral falcon
#

My eyes!! πŸ˜„

naive pawn
naive pawn
#

are you suggesting a singleton

astral falcon
burnt vapor
#
if (ColorUtility.TryParseHtmlString("#8C0000", out var color)
{
  GameObject.Find("Global Light 2D").GetComponent<Light2D>().Color = color;
}
cerulean badger
burnt vapor
naive pawn
#

you sure .Color exists?

burnt vapor
#

Maybe in your case log a warning if the parse failed

cerulean badger
astral falcon
burnt vapor
#

Alternatively do this:

if (!ColorUtility.TryParseHtmlString("#8C0000", out var color)
{
  Debug.LogWarning("Failed to parse color");
  return;
}

GameObject.Find("Global Light 2D").GetComponent<Light2D>().Color = color;
#

Considering you probably want it to work every time

rich ice
#

is there any reason why you're using hexadecimal in the first place?

cerulean badger
burnt vapor
#

Additionally, and I believe twentacle was already pointing this out, I strongly suggest you improve the way "Global Light 2D" is found. Find type method are ugly, perform poorly and are easy to break

#

If you have a single instance, consider making a singleton that holds a reference to "Global Light 2D"

naive pawn
burnt vapor
astral falcon
#

Okay, lets wrap your needs up. Do you need to change it from runtime at all?

#

And do you need hex codes? (you said no, right?)

rich ice
cerulean badger
astral falcon
#

then take jordands suggestion, just use a Color property

burnt vapor
cerulean badger
cerulean badger
burnt vapor
#

If that confuses you I strongly suggest you take basic Unity lessons. SerializeField is a very common attribute to use

visual linden
#

I suspect it's the diff formatting that's confusing to someone not used to reading it

rich ice
cerulean badger
burnt vapor
#

I am obviously very direct with "go learn basic Unity" but this is super common to do in code

#

You generally don't expose variables to literally everything, and instead make it private. However, the inspector will then not show the variable. This is where SerializeField makes the difference as it will then be shown again.

cerulean badger
#

so it allows me to make a private variable that still shows up in inspector and other scripts?

visual linden
#

Well, not other scripts

cerulean badger
#

oh, easier than I expected lol

visual linden
#

The point of a private variable is to keep it private, but the serializedfield attribute tells Unity to still expose it in the Inspector window

burnt vapor
#

Encapsulation as it's called

#

Generally you want to avoid access as much as possible to keep behaviour clear. Anything that must be accessed should only be made available through either script properties and/or methods

cerulean badger
#

hmm got it

burnt vapor
#

On that note, here's another diff. This time explaining how you can use a property to just provide the ability to get a value, and not modify it from another script.

- [SerializeField] private Color _lightColour;
+ [field: SerializeField] public Color LightColour { get; private set; }

I don't expect you to understand this

#

All in all there's various different ways to do this. When in doubt you can always just make a basic public field, but you should definitely consider learning encapsulation

cerulean badger
#

that's why I'm the music guy and not coder notlikethis

visual linden
#

When in doubt you can always just make a basic public field
I think this is the thing to keep in mind, especially when starting out. It also goes for most other things.
Step one is to get things working, step two is to improve.

sharp abyss
#

I have a game like this. I want you to ask about in which conditions do you think the enemy or the character should take damage, because even if I am not controlling the arm and weapon touches the enemy gets damage.There is a cooldown to get damage.I thought about checking velocity and if I am controlling the arm to make taking damage happen. But velocity of weapon also has the bodys so that didnt come logical to me.Maybe multiplying the damage by velocity make the combat more physical.What are your thoughts?

cerulean badger
#

imo it could be either ur idea of multiplying or checking if arm control input is being used

sharp abyss
#

I will try both

bright arch
#

when does code in different scripts run, relative to each other? same frame?

swift crag
#

"scripts" is a bit of a vague term here

wintry quarry
#

If you're talking about Update, it runs once per frame for each one. So yes by definition they will all run in the same frame. The order is essentially random.

rich ice
swift crag
#

if you're talking about the components you've created -- which you did by creating classes that inherit from MonoBehaviour -- Unity invokes various methods on them through the life of the component

frigid sapphire
#

If I made a list with floats (example a list with multipliers for different things) would there be a way to multiply all of them by 3?

swift crag
#

(notably, you'd need to use a for loop to be able to assign the result back into the list)

wintry quarry
#
for (int i = 0; i < myList.Count; i++) {
  myList[i] = myList[i] * 3;
}```
swift crag
#

foreach would not permit you to change the contents of the list

burnt vapor
#

The easiest way would be with Linq and Select, if you know what that is

#

myList = myList.Select(x => x * 3).ToArray()

rich ice
swift crag
#

(there is a ToList method)

#

that'll at least prevent you from allocating twice as much garbage as needed

wintry quarry
#

Notably Linq will create a whole new list which isn't good for performance.

burnt vapor
#

Ah yes, I didn't notice they mentioned it was a list

frigid sapphire
#

Yeah I do not understand anything that weas just said to me (first time using lists)

burnt vapor
#

Well yeah, I meant easiest, not least allocation

swift crag
#

If you have no clue what anything we just said means, you need to learn how C# works

#

!learn

eternal falconBOT
#

:teacher: Unity Learn β†—

Over 750 hours of free live and on-demand learning content for all levels of experience!

burnt vapor
#

Usually with questions here I'd resort to the easiest approach and not provide one with less allocation just because

#

Assuming the easiest approach is not some gross hack of course

swift crag
#

LINQ is a leap in its own way, of course

wintry quarry
#

literacy with basic for loops should be encouraged 😭

swift crag
#

you're introducing anonymous functions

frigid sapphire
wintry quarry
burnt vapor
#

Yeah, this does assume that you have knowledge of LINQ

frigid sapphire
#

Thanks

wintry quarry
burnt vapor
#

Hard to say what experience each person as ofc

gleaming turtle
#

Anyone know why my mesh collider is completely off even though i've provided it a mesh that is correct?

bright arch
# bright arch when does code in different scripts run, relative to each other? same frame?

thanks everyone. bonking my head on the wall with this one lol, im using events and two scripts have subscribers. one is logic code, and it activates a "busy" state, the other is the visuals for the logic, which i only want to happen ofc if it is not busy. my issue is just that the logic sets itself as busy if it isnt already busy and then executes code, while the visual executes code if it isnt busy. which means the visual happens after the logic, even tho theyre called by the same thing (mouse click). just sorta wondering where to sort this out or if im just thinking of it incorrectly.

swift crag
visual linden
#

It's also marked Convex

wintry quarry
#
  1. This isn't a code question
gleaming turtle
#

Well cheers for the help anyway πŸ‘

gleaming turtle
rich ice
swift crag
#

They don't all execute "simultaneously"

wintry quarry
swift crag
#

Similarly, Update methods don't run "all at once"

#

they run one at a time, in some arbitrary order

bright arch
#

ill try it anyway but this is interesting thank you

wintry quarry
swift crag
#

That would freeze the game!

wintry quarry
#

You probably have a misunderstanding of how coroutines work

#

Sharing your actual code and what you're trying to do would go a long way to understanding your issue though

visual linden
#

It sounds to me like they just want to yield for an initial amount of time inside the coroutine, to allow for other code to execute first?

#

If you run StartCoroutine(myCoroutine) and then inside the coroutine yield using
yield return new WaitForSeconds(amount); , your coroutine will only continue after the time has passed.

swift crag
#

It sounds to me like they just have an order-of-operations problem that they're trying to fix with a delay

wintry quarry
#

Sounds to me like they think an event listener that starts a coroutine will itself wait for the coroutine to complete

#

that too

swift crag
wintry quarry
#

We're just speculating though

swift crag
#

indeed

visual linden
strong wren
#

Unless I'm misunderstanding the question

swift crag
wintry quarry
#

This all has the strong feeling of an XY problem to me!

bright arch
#

my code:

this is part of the logic script

    {
        if (Input.GetMouseButtonDown(0))
        {
            OnSnapPhoto?.Invoke(this, EventArgs.Empty);
        }
    }

    private void SnapPhoto(object sender, EventArgs e)
    {
        if (!busy)
        {
            Debug.Log("Not busy!!");
            busy = true;
            currentPhotos++;
            if (currentPhotos == maxPhotos)
            {
                Debug.Log("Yahoo");
            }
        }
        else
        {
            Debug.Log("Whoops, busy");
        }
    }```

and this is part of the visuals script

```    private void Logic_OnSnapPhoto(object sender, EventArgs e)
    {
        if (!logic.busy)
        {
            Debug.Log("Snap!");
            image.color = new Color(1, 1, 1, 0);
            camCullMask = playerCam.cullingMask;
            camClearFlags = playerCam.clearFlags;
            playerCam.cullingMask = 0;
            playerCam.clearFlags = CameraClearFlags.Nothing;
            UpdateString();
            StartCoroutine(nameof(CameraClick));
        }
    }

    public IEnumerator CameraClick()
    {
        Debug.Log("Started click");
        yield return new WaitForSeconds(0.1f);
        image.color = Color.white;
        yield return new WaitForSeconds(1);
        playerCam.cullingMask = camCullMask;
        playerCam.clearFlags = camClearFlags;
        logic.busy = false;
        yield break;
    }

its a bit confusing probably if you dont know what exactly is going on here but basically im taking pictures in the game, the visuals make it so you can see the picture you took for 1 second, but i dont want to allow the player to take multiple pictures while youre previewing the picture so thats what the busy state is for. i want to decouple logic from visuals as much as possible so thats why i dont use a busy variable in the visuals script, though now that i think about it if i just set two variables independent of one another in each script for their own separate "busy" timing then that can solve it.

sorry for text wall

visual linden
#

though now that i think about it if i just set two variables independent of one another in each script for their own separate "busy" timing then that can solve it.
This sounds like a reasonable solution to me :)

swift crag
#

The mouse click should do nothing but ask the camera to take a photo.

wintry quarry
# bright arch my code: this is part of the logic script ``` private void Update() { ...
  1. Don't use the EventArgs pattern in Unity. It leads to unecessary object allocation and garbage collection, plus lack of type safety for the "sender" object parameter. Just use a defined Action type or a custom delegate type that has the actual parameters you need.
  2. Why does the "logic script" have a listener to its own event? Can't you just call SnapPhoto before or after the event is raised?

If I'm understanding the issue is SnapPhoto being run in the wrong order with some other listener?

swift crag
#

If the camera says "yes", then it should go and run some other code.

visual linden
#

I see we're jumping at the chance to do a code review πŸ˜…

swift crag
#

It doesn't make sense to have SnapPhoto set busy to true and then CameraClick set it back to false

#

That's why you're having problems -- the exact order of execution between SnapPhoto and Logic_OnSnapPhoto matters

bright arch
#

thank you very much

#

i appreciate it greatly everyone :)

swift crag
#

We could try to find the absolutely simplest way to fix the current issue, yes, but that wouldn't be helpful

bright arch
swift crag
#

the C# documentation makes it sound like EventArgs is some kind of magical type you have to use with the event keyword

languid spire
#

what? EventArgs is just a class like any other, nothing special about it at all

swift crag
bright arch
#

youre very correct

languid spire
bright arch
swift crag
#
[SerializeField] private float photoDelay = 1f;

public event System.Action OnTakePhoto;
public event System.Action OnReady;

private float nextPhotoTime = -1f;
private bool ready = false;

void Update() {
  if (!ready && nextPhotoTime <= Time.time) {
    ready = true;
    OnReady?.Invoke();
  }
}

void TakePhoto() {
  if (ready) {
     nextPhotoTime = Time.time + photoDelay;
     ready = false;
     OnTakePhoto?.Invoke();
  }
}

This would let you react to both taking a photo and the camera becoming ready again.

#

The camera itself is responsible for making itself ready again

bright arch
#

fen is the goat

#

unrelated, how do you make the code block coloured?

swift crag
#

```cs
code here
```

#

I'm not sure I'd use events at all here, though -- maybe if I had lots of different unique features that various kinds of cameras had?

#

Events (or lists of delegates) give you flexibility in what code gets run in response to something happening

bright arch
#

if im honest i find the events really confusing still so my neanderthal brain wants to avoid them but learning to use different things is always good

swift crag
#

In this case, though, displaying the photo on the screen is pretty integral to how your game's camera works

visual linden
swift crag
naive pawn
swift crag
#

I use events any time I want to react to something happening, like an entity being destroyed or a setting being changed

visual linden
swift crag
#

That class gets constructed when you call the method

#

you can indeed hang on to a single WaitForSeconds that gets reused by every coroutine, though

visual linden
#

That was my thought

#

But this was all just on a sidenote

#

Don't let me distract

bright arch
#

ill let what you all suggested lay in my brain before i continue to do anything, but thanks again. how important is it that garbage is not created, what IS garbage, and is there a way to remove it naturally (ie maybe swapping scenes? idk)

swift crag
#

I would not worry about that at all right now, but in short: when you create an object, it takes up memory. When you lose all references to the object, it eventually gets cleaned up by the garbage collector

#
int[] what = new int[100000];

if you throw this in an Update method, you'll eat up a ton of memory every frame

#

This will force the garbage collector to run regularly

#

garbage collection is expensive and can cause a noticeable hitch in your game

polar acorn
rich ice
#

clearly a bnuuy bnuuy_real3

bright arch
#

looks like hyena sk_nodA

frigid sapphire
#

Hi, I made a thing that either gives you some money or multiplies all income by 3x. The script is on a prefab and for some reason it doesnt set the bool to true even tho it should (idk how to explain it better) https://paste.ofcode.org/rcsQXCihi2cFnFU9GvjE2e

polar acorn
frigid sapphire
#

Yep

polar acorn
#

The condition it's set in is never running

#

Random.Range is max exclusive. Random.Range(1,2) can roll 1 or 1

#

Er, wait, that'd mean it'd always hit the else

#

So, two separate problems

#

Wait, also that's a float random. Three problems

frigid sapphire
#

I am aware of the Random.Range thing i just set it to let me spawn it more often

frigid sapphire
polar acorn
frigid sapphire
#

ohh so it can roll decimals too?

polar acorn
#

That's what a float is

naive pawn
#

Random.Range(1f, 2f) can result in 2f, or any other float between 1 and 2 inclusive

#

Random.Range(1, 2) will result in exactly 1, as an integer

echo ruin
#

Flot makes it possible to get 1.35683 coin

frigid sapphire
#

Just didin't think that it would work the same on random lol

#

Well only issue I'm struggling with rn is that bool not setting

polar acorn
#

First off, try logging the bool after you set it. See if that code runs

echo ruin
#

I can’t view the entire script on my phone lol

frigid sapphire
naive pawn
frigid sapphire
polar acorn
echo ruin
#

Cause inspector settings overrides public varibles

frigid sapphire
#

(Instantiate)

polar acorn
#

Look at that one

frigid sapphire
#

It gets destroyed on click

polar acorn
frigid sapphire
#

How else could I make it true when rolling the 3x?

polar acorn
#

Every single instance of this BigMoney script is going to have its own xExist boolean

echo ruin
#

The script tells it to change bool to true and then delete the object. Hence you wont find an active object with a true bool

polar acorn
#

The one on the prefab, the one you spawn in, any other copies, etc.

frigid sapphire
#

Ohh that makes sense now

polar acorn
#

So, since this object ceases to be, then nothing holds that data

frigid sapphire
#

So just make the bool in a different script?

#

And then set it to true via BingMoney

polar acorn
#

Yes, have the button tell that script to change whatever boolean

echo ruin
#

You could

frigid sapphire
#

Will give that a shot

polar acorn
#

Also, just want to point out: You're adding four things to your mult list every frame. Probably don't want to do that. You're also calling GetComponent four times for the same component every frame. Definitely don't want to do that

frigid sapphire
#

Isn't the list capped at 4 though?

polar acorn
#

No, why would it be?

#

Lists have variable length

frigid sapphire
#

mults = new List<float>(4);

polar acorn
#

that's the point of lists over arrays

polar acorn
#

Then you add four more things to it every physics step

frigid sapphire
#

Oh I thought that was the cap😭

#

And about the get component one, how else would I access the variable via prefab?

echo ruin
#

Change FixedUpdate to Start

polar acorn
#

then reuse that

#

You should get the object and its component in start, then if you need the values to update every frame, use that variable in Update

frigid sapphire
#

Thanks

echo ruin
#

Also careful with adding things to a list more than once. It doesn’t check whether the item already exists in the list, so it will be added again

frigid sapphire
rich adder
swift crag
#

The list is still empty

#

The capacity determines when it'll have to reallocate its internal storage

#

I've gotten confused by that more than once

polar acorn
#

Ah, I figured it created a list of that length, which would populate with default

#

🌈 ⭐ The More You Know

rich adder
#

wrong reply srry lol

frigid sapphire
#

Oh youre right same mistake as last time with the getcomponents

rich adder
frigid sapphire
#

Inspector on the main script

rich adder
#

also you should really be using arrays when you have such variables numbered

frigid sapphire
#

mult, acm, p4m, p5m

#

those are the multipliers

rich adder
#

also kinda strange this is FixedUpdate insead of update

frigid sapphire
#

Yes timer is going down

rich adder
#

also starting a new coroutine every physics frame seems like a recipe for disaster

frigid sapphire
#

Will move that to start now

rich adder
#

or its just timer based ?

frigid sapphire
#

Well it's suppossed to be running at all times, spawns like a golden waffle every set time

rich adder
#

oh okay, well use Update then
but dont call StartCoroutine(Chance()); every frame, give it specific conditions and if anything store it in a Coroutine type variable to maybe stop it as needed etc

frigid sapphire
#

Maybe just put a while loop in the coroutine?

echo ruin
#

Your game might freeze

rich adder
#

sure you can do that as well if you want to endlessly runn

#

as long as you put a yeild return null in loop, it will not freeze

echo ruin
#

True, if it's within the while loop

rich adder
#

but yeah one must be careful with while loops because they will freeze your code, esp if not in an "async"ish function like coroutine

rich adder
frigid sapphire
rich adder
#

debugging and its power

#

if its 0 its not running a for loop, because looping over 0 is no loop lol
0 != 0 < 0

frigid sapphire
#

void Start() { mm = GameObject.Find("Main"); ms = mm.GetComponent<MainScript>(); gg = mm.GetComponent<GoldGofr>(); mults.Add(ms.acm); mults.Add(ms.mult); mults.Add(ms.p4m); mults.Add(ms.p5m); } void FixedUpdate() { mults[0] = ms.acm; mults[1] = ms.mult; mults[2] = ms.p4m; mults[3] = ms.p5m; }

rich adder
rich adder
frigid sapphire
#

Nope I have no clue yet

#

Cause it's clearly suppossed to add 4 things to the list but it's not??

rich adder
frigid sapphire
#

Debug.Log("Is start running"); and got nothing lol

#

did I actually manage to misspell Start

languid spire
#

no, you just did not attach this script to a gameobject

rich adder
frigid sapphire
#

It's a prefab

rich adder
#

do you ever spawn it then ?

#

also doesn't answer the question

frigid sapphire
#

Yeah every 1-2 mins

visual linden
#

Could there be some exception thrown in the Console halting the execution?

frigid sapphire
#

A bunch of 0s

rich adder
#

also make sure the messages are not collapsed

languid spire
rich adder
#

also this ^

frigid sapphire
rich adder
#

why not just enable and disable the same one instead of instantiating a new one

frigid sapphire
#

Good question, I have no aswer for it tho

languid spire
frigid sapphire
#

Its in the assets should be active tho, everything worked before I moved the List part into Start

#

It was in update before

visual linden
#

I know this is #πŸ’»β”ƒcode-beginner , but I feel like if we could point @frigid sapphire towards some Debugger resources, simply stepping through the code with a couple of breakpoints would probably solve this mystery.

rich adder
#

also if Update ran, Stat most certainly ran

frigid sapphire
rich adder
# frigid sapphire

the script doent run unless its on a gameobject in the scene and active

frigid sapphire
#

How did update work then?

#

Ohhhh cause it was in update the list got created when it spawned?

visual linden
#

πŸ€”

frigid sapphire
#

I will move it back to update and check

languid spire
#

that's just nonsense, Start will run on the instantiated object

rich adder
#

If debug is not running in Start, you have the script disabled somehow or not active gameobject. No other ways around it, if update runs

#

start will always run if update has ran

frigid sapphire
#

Everything else is running

#

oh wait huh my timer has just stopped going down

#

oh right yield return null disregard that

rich adder
frigid sapphire
#

I can give all 3

#

actually i'll just give the 2 cause main script has like 460 lines

rich adder
frigid sapphire
#

Deleted now

rich adder
#

why..you are still debugging

frigid sapphire
#

I am yeah

#

Well while loop decided to freeze unity, hope i made a saveπŸ•―οΈ πŸ™

rich adder
frigid sapphire
#

second link

polar acorn
#

It's a gnarly loop and I saw how far indented it was and thought "I aint reading all that"

rich adder
#

yeah that intent is wild

#

you missed yield return null outside the brackets

#

you need to learn Early Return pattern so you are not nesting 100 things
if(condition == false) return;
instead of
if(condition == true) { //dostuff

polar acorn
#

That's way too many conditions. I think it might be worth taking a step back and thinking if there's a better solution to this than a while loop in a coroutine

frigid sapphire
#

It was calling the coroutine every tick but I decided to just put it in a while loop

polar acorn
#

It looks like this is mostly checking a bunch of conditions, and if they're all met, it runs some code that has waits in it. There's zero reason the checks can't just be in update and only that innermost payload in a coroutine

#

Just have some sort of boolean that prevents you from starting the coroutine multiple times

rich adder
#

also yes most of this can just go in Update

#

but if you do keep corotine for delay simplicity make at least a condition / store it in a variable so you don't start a new one every frame

frigid sapphire
#

This server is such a gem, never seen so many people this smart in a server before this info is starting to overload my brain a lil haha

rich adder
#

tbh you overcomplicated the system a bit

#

you dug yourself deep, you must instead of keep digging you have to get out retrace your steps to a better path

frigid sapphire
#

Yeah this is pure improvising

rich adder
#

improvising can work too but you kinda need to have system already tried by yourself

#

build as you go can sometimes lead to harder dead ends to get out of

#

good code starts with a well planned/thought out system, even if you need pen and paper

frigid sapphire
#

Yeah I managed to get everything to work again but multipliers still not 3x'ing

#

I think i'll just delete the list and do it the old fashioned way

frigid sapphire
frigid sapphire
#

the second one, the multipliers are stored on the 3rd one tho

#

2nd one is supposed to triple the values in the list but its either that the list is empty or its just not tripling them

rich adder
#

jesus..

#

you reaalize this is adding 4 entries to your list every physics frame

frigid sapphire
#

Yep it was in start first but nothing happened so moved it to update to see if it'll work

swift crag
#

i should point out that these are very bad names

#

I can't tell what this is meant to do

naive pawn
#

that's the new playstation product, obviously smh

rich adder
#

yeah I suggest this to OP earlier, legibility is more important than working code

naive pawn
rich adder
frigid sapphire
#

acm is auto cursor multiplier
mult is just click multiplier
p4m is something 4 multiplier (i forgor)
and p5m is something 5 multiplier

#

ms is just main script

swift crag
#

if even you don't know what these things mean, then you have a serious problem

rich adder
#

we know what the scripts are for (by your description) but they are messy and hard to see whats going on esp in script 3

frigid sapphire
rich adder
#

a lot of these problems would literally be solved by just learning arrays lol

swift crag
frigid sapphire
#

Yep

rich adder
swift crag
#

They will not. The list stores copies of those values

#

float is a value type; it is always copied and never shared

frigid sapphire
#

bm.mults[i] = bm.mults[i] * 3; ms.acm = bm.mults[0]; ms.mult = bm.mults[1]; ms.p4m = bm.mults[2]; ms.p5m = bm.mults[3];

#

isnt this updating it?

swift crag
#

Yes, that would change them.

#

the first line tries to multiply something in the list by 3 (whatever i happens to be at that moment)

#

the following four then set four fields on the "main script" object

frigid sapphire
#

Omg I thought "i" was everything in the list

swift crag
#

...no

frigid sapphire
#

Well there is my solution

#

To the 2 hours of debugging and asking questions

swift crag
#

I think you need to stop whatever on earth it is that you're doing and use !learn to get a handle on how C# works

eternal falconBOT
#

:teacher: Unity Learn β†—

Over 750 hours of free live and on-demand learning content for all levels of experience!

swift crag
#

You're going to have a much better experience if you aren't stumbling around in the dark

rich adder
#

yes having more tools (code / functions) are your disposal will yield better code

naive pawn
#

you could (but absolutely should not, this is a joke) make mults a Vector4 and do bm.mults *= 3;

#

πŸ™ƒ

swift crag
polar acorn
#

Honestly it seems like a better solution is to just give whatever ms is a globalMult property, and use a read-only property that takes the base value and multiplies it by globalMult

#

Then you just set the mult on that thing, and whenever you ask it for, like, ms.acm, it'd return _acm * globalMult

frigid sapphire
#

How could I multiply all the contents of a list?

swift crag
#

note that there is more to that code than just list[i] = list[i] * 3; ...

frigid sapphire
#

that weird tho I did that at the start and it worked but now it just stopped multiplying it

valid vector
rocky canyon
wintry quarry
#

Also just FYI your mouse look code has a bug/weirdness:

        float mouseX = Input.GetAxis("Mouse X") * sensitivity * Time.fixedDeltaTime * sensMultiplier;
        float mouseY = Input.GetAxis("Mouse Y") * sensitivity * Time.fixedDeltaTime * sensMultiplier;```
Time.fixedDeltaTime does not belong in there. It's making your have to put a sensMultiplier value that is 50x larger for no reason
rocky canyon
#

no need to scale it ^ mouse delta's work regardless

#

the only thing u need is sensitivity multiplier

#

once/if u remove it.. then u can modify ur values to work as it did b4

valid vector
#

ok because i was trying to get gravity to be towards an object

wintry quarry
#

set the gravity with Physics.gravity = myNewGravityVector;

valid vector
#

yeah but also things like the jump and "extra gravity" in the movement code confuses me

wintry quarry
#

Yes that extra gravity code will be a problem if you change the global gravity vector

#

you could fix it by having that line incorporate global gravity vector instead of hardcoding Vector3.down

rocky canyon
#

it is a dani project.. πŸ€ͺ

wintry quarry
#

but the Time.deltaTime there also makes no sense at all

#

Yes, this is written not by a game developer but by an entertainer/YouTuber who has a lot of poor practices

rocky canyon
#

and he publicly admits it..

#

meme-code πŸ˜„

#

but.. if u learn from it.. im not hating on it πŸ‘

#

but theres lot to be improved.. but you'll get there

valid vector
#

im pretty sure not even he doesnt knows how it work

rocky canyon
#

im almost 50% sure theres some code in his game he copy and pasted w/o any knowledge of it yea

eternal falconBOT
wintry quarry
rocky canyon
#

ive even seen sections of his tutorials where he "yoinks" code from online

#

and just moves along

valid vector
#

i just want something that works

rocky canyon
#

is it close?

valid vector
#

it works as long as you dont want to edit

rocky canyon
#

if u just want something that works

valid vector
#

i want something that works and works

#

i feels different

rocky canyon
#

the asset i just sent is recommended by tons of people.. its a kinematic rigidbody controller.. so kinda the best of both worlds..

#

CC and RB

#

it can be tuned to make it probably exactly what u already have

#

but it took me 6 months or so to my my CC when i started learning.. and i ended up using dozens of tutorials

#

soo... dont feel discouraged..

#

it takes time sometimes especially if u want to absorb the information ur playing with

valid vector
#

also this is just a funny little project and my other game is

#

entirely built on the other code

#

most of the game is just how the player moves

rocky canyon
#

oof, u should be trying to get away from that.. modularity is key

#

but ur original question has been answered.. soo imma leave it at that πŸ™‚ good luck mate

valid vector
#

like taking the portals out of portal

rocky canyon
#

well dont do that then..
the movement would usually only affect the movement...

if u remove the controller to change it w/ another controller and all of a sudden ur game isn't a game anymore... u really really been coupling too much to that controller

#

can pause the game.. completely remove my player.. and drop in a new one.. and carry on

valid vector
#

well then this quick experiment game wouldnt work either

#

because i was looking at my game and i thought what if mario galaxy

#

so if that game wouldnt work without the controller

#

this one wouldnt either

rocky canyon
#

i never got a good grasp on the type of game i wanted ot make while i was learning

#

πŸ˜„ i musta changed my mind 100 times

true owl
#

Hey I'm a little lost right now, I made this input system I want to have a dash kind of like Celeste but it seems that I get some kind of error.

InvalidOperationException: Cannot read value of type 'Vector2' from control '/Keyboard/leftShift' bound to action 'Player/Dash[/Keyboard/leftShift]' (control is a 'KeyControl' with value type 'float')
UnityEngine.InputSystem.InputActionState.ReadValue[TValue] (System.Int32 bindingIndex, System.Int32 controlIndex, System.Boolean ignoreComposites) (at
#

my code is just this

  void OnDash(InputValue value)
    {
        dashingInput = value.Get<Vector2>();
        // if (canDash)
        // {
        //     isDashing = true;
        //     canDash = false;
        // }

        Debug.Log(dashingInput);
    }
astral falcon
rocky canyon
#

i dont know a whole lot about the new input system.. but ive seen similar errors elsewhere..

#

seems like ^ that is ur issue

true owl
#

but i thought i made it output vector 2

polar acorn
languid spire
# true owl

read the error message, it tells you what you did wrong and how to fix it

polar acorn
#

A Vector2 control type is going to need more than just a button to define it

astral falcon
# true owl

you say, dash is vector2, but pressing a key is never a vector2 because pushing is only one axis

rocky canyon
#

this think about it

polar acorn
#

It contains two values, X and Y. Shift is only going to give you one of those

true owl
#

I guess that's true

#

Would I have to make it like the WASD which is predefined?

rocky canyon
#

WASD works b/c theres (2) keys tied to the single value
a positive and a negative

polar acorn
#

I don't think "Dash" makes sense to be a Vector2

#

It sounds like you want a boolean

true owl
#

I want to contain the direction of the dash though, one of 8 directions

astral falcon
#

you just want to activate the dash, right? The direction should (most likely) be in the direction you are facing with your character

rocky canyon
#

u can do that by reading ur direction

astral falcon
#

Ah, so you want to activate like a target system?

true owl
#

I guess kind of? I want it so if I'm holding W+D it'll go to top right for example

astral falcon
#

or where do the players decide on those 8 directions?

#

so, its in the direction of your player

#

but clamped to 45 degrees movement

true owl
#

yeah

rocky canyon
#

my controller works by grabbing the Directional Input when the dash is pressed..

or maybe even just using velocity
ahh (yea.. that last comment of twentacle) mine doesn't lock it into a cardinal direction... it can dash anywhere between 0 -360

polar acorn
#

and then check if you're pressing the dash button

true owl
#

ah

astral falcon
#

You just gotta project your vector2 to the 360 radius and step it to 45 , there you go with your direction

true owl
#

interesting

astral falcon
#

Of course, oversimplified, but thats what you tell the code to do in the end πŸ˜„

polar acorn
#

Remember - it's an input map. You're binding to buttons. Having a "Dash stick" doesn't really make sense

true owl
#

so my Dash should just be a boolean to check whether or not the dash has been pressed, then map that with whatever my player is currently pressing

polar acorn
#

You would normally press a dash button, and dash in the direction of the movement stick

rocky canyon
#

ya, it doesn't need to be tied into direction at all... (the dash input that is)

#

u just check direction/input when u read/use the dash

#

then use logic to tie the two together

astral falcon
#

ya, right. As we all assume, your movement is also tied to that 45 degree step system, you can just force your player into that direction when dashing

rocky canyon
#

if ur player is already facing the direction u tend to dash.. u could just use the transform.forward

#

but thats just an assumption

true owl
#

dang

#

this is rough

#

Alright

#

I have a moveInput already from my onMove, so I'll try using that I think

autumn osprey
#

hey, sorry to interrupt! i'm currently working on jump mechanics for a 2D character, and i'm struggling with this one portion significantly. i'm trying to make it so that the longer you hold down space, the higher the character jumps.

In FixedUpdate() this code runs:

        //Jumping
        if (Input.GetKey(KeyCode.Space) && isGrounded) 
        {
            StartCoroutine(Jump());
        }```

Triggering this:
```c#
private IEnumerator Jump() {
        float cooldown1 = 1;
        while (Input.GetKey(KeyCode.Space) && cooldown1 > 0) {
            body.velocity = new Vector2(body.velocity.x, 12 + -3*(cooldown1 - 1)); //.998 - 1 = -.002

            cooldown1 -= Time.deltaTime;
        }
        yield return null;

    }

What I'm trying to do is have it so that the character has a velocity range between 12 and 15, depending on how long they hold jump. What is actually happening is that it is set to the max range no matter how long you hold the button, regardless of how long the timer is adjusted for.

I could be misunderstanding basic physics, or there could be a problem with my code here or where it is called. I appreciate any advice. Once I get this working with velocity, I plan to change it to work using AddForce() to match how I'm coding horizonal movement; so any advice on how to get that working smoothly is also appreciated. I worked on this for about 3 hours yesterday trying various methods I saw, and just had a lot of problems lol.

astral falcon
wintry quarry
#

therefore the entire loop will run within a single frame

#

What twentacle said is also a problem

autumn osprey
astral falcon
#

ah true, if thats the case that its not grounded within the next step

autumn osprey
astral falcon
#

but Jump should be running on its own, as its a coroutine

#

Or am I missing something here πŸ˜„

autumn osprey
astral falcon
#

Could you put a debug.log in your coroutine and see how often it gets fired when you hit space?

#

in general, logs about the states you desire should always be included, to actually know whats going on

autumn osprey
#

honestly, haven't really used debug.log too much yet (i am aware that is dumb), but i'm going to edit this with a few of the suggestions given and come back either with a fixed script or more problems

astral falcon
rocky canyon
#

even after 3 years i still use them for everything

swift crag
#

I want to figure out a better way to categorize my log statements

rocky canyon
#

same.. 😦

swift crag
#

ideally I'd have a hierarchy of them that I can toggle

rocky canyon
#

even after color and formatting i still would rather have a better way..

swift crag
#

ooh, wait, I have an idea

rocky canyon
#

still need to collapse and uncollapse everything

#

theres too much info at times so i use a 1bar approach

#

but then i need 2 bars.. and so on and so on lol

#

i think imma make a better way to organize them on screen (just to avoid overlaps) and i'd also like to make a toggle key to show/hide them at command

swift crag
#

I have some of that

swift crag
# swift crag ooh, wait, I have an idea

I want to be able to do this:

Logger.Log("Oh my god it broke", Foo.Bar.Baz);

Turning on the Foo category or the Foo.Bar category or the Foo.Bar.Baz category would all let me see this message

#

Figuring out how to write Foo.Bar.Baz in C# is the nuisance. You can't nest enums

rocky canyon
#

mine uses Dbug.Log

naive pawn
rocky canyon
#

and i have

#

i tried to use something like D.ebug and D.raw

naive pawn
#

that feels so cursed lmao

rocky canyon
#

but not so much intuitive enuff for me

swift crag
#

too clever

astral falcon
#

I got my own debug logs that change color depending on the class type

#

And will run async, as anything besides debug.log itself wont run besides main thread afaik

rocky canyon
#

noooice

naive pawn
#

is it GetType().Name.GetHashCode() % 0x1000000?

rocky canyon
#

its not as cursed as it seems.. i wrote it a while back.. never had to change it.. my log can run almost regardless of what u give it

astral falcon
shell sorrel
#

i just never needed that much control, most logs are tempoary and i remove when no longer needed

#

so its mostly just general flow stuff

rocky canyon
#

hang on i was just about to mention the stacktrace

shell sorrel
#

then i will just use breakpoints for most

astral falcon
shell sorrel
#

can breakpoint on devices just fine

shell sorrel
#

do it all the time for console and mobile

astral falcon
shell sorrel
#

also it does not need to stop

rocky canyon
#

the only thing i haven't fixed w/ mine is a way to go directly to the instance that calls the method

shell sorrel
#

i can have the breakpoint just log

rocky canyon
#

so i have to go to the bottom of the trace 😭

astral falcon
# rocky canyon

But excluding the stacktrace will still open the logger when double click, right?

swift crag
#

Now I'm thinking about this again

#

this week's dev log: have you guys ever heard about bikesheds?

swift crag
#

being able to include context is amazing

#

I have validators that look for missing references, bogus localized strings, etc.

#

the resulting logs can take me directly to the Bad Object

astral falcon
rocky canyon
rocky canyon
#

lol

#

ur more advanced than me clearly

true owl
#

okay so I updated my code for the dash to be like this, but there's a couple issues. It doesn't seem to really dash, it's kind of more like a jump. He can't dash horizontally either, only vertically and diagonally (up).

void OnDash(InputValue value)
    {
        if (value.isPressed)
        {


            Vector2 dashingDirection = moveInput;
            Debug.Log("Dashing direction");
            Debug.Log(dashingDirection);
            if (canDash)
            {
                isDashing = true;
                canDash = false;
            }

            // If not pressing anything, dash in the direction player is currently facing
            if (dashingDirection == Vector2.zero)
            {
                Debug.Log("Is Actually Zero");
                dashingDirection = new Vector2(transform.localScale.x, 0);
            }

            // Actual dash implementation
            if (isDashing)
            {
                Debug.Log("Should be dashing");
                Debug.Log(dashingDirection.normalized * dashingVelocity);
                myRigidbody2D.linearVelocity = dashingDirection.normalized * dashingVelocity;
                return;
            }

            // if you touch the ground you are able to dash again
            bool isGrounded = myCapsuleCollider.IsTouchingLayers(LayerMask.GetMask("Ground"));
            if (isGrounded)
            {
                canDash = true;
            }
        }
    }
#

Also when standing completely still he doesn't dash at all.

wintry quarry
#

That's my guess

true owl
#

I also have in my update method this coroutine StartCoroutine("StopDashing");

astral falcon
wintry quarry
true owl
#

Sorry about that

#
    {
        yield return new WaitForSeconds(dashingTime);
        isDashing = false;
    }```
#

this is the coroutine

wintry quarry
#

ok but what does that have to do with the dash code you shared?

#

seemingly nothing

#

And why would you start that coroutine every frame?

#

That means you will set isDasing to false on basically every frame

true owl
#

From my understanding I thought this would kind of stop all other movement of the player until that time frame ends?

wintry quarry
#

You haven't shared it so we can only guess

#

It would probably be simpler to just share the full script

#

!code

eternal falconBOT
true owl
#

oh gotcha

#

thanks for the help in advance

wintry quarry
#

your code is doing this every frame

#

the dashing stuff is going to be completely overwritten

astral falcon
#

and this too

wintry quarry
#

yeah starting the coroutine every frame is absolutely wrong

astral falcon
#

Woops, huge pasted image, sorry

true owl
#

i see

wintry quarry
#

That's something you should do when you start dashing

#

not every frame

true owl
#

so how would I go about fixing this, shouldn't run be called every frame?

wintry quarry
#

and your movement code will need to care about the isDashing variable for the dashing not to be overwritten

wintry quarry
true owl
#

Should I just not do a method called run and have a huge movement method instead or

wintry quarry
#

that's a structural question that has little to do with the actual problem

true owl
#

I guess

rocky canyon
# astral falcon oh nice, i just googled randomly for it and found a solution to it, its just a u...

my on-screen debug panels are the worst..
its in my static Utils class and i wasn't sure how to do it.. since its GUI stuff

public static void RealtimeDebug(string text, Vector2 position, int fontSize, Color textColor, Color outlineColor, int outlineThickness, int padding)
{
    GUIStyle style = new GUIStyle(GUI.skin.label)
    {
        fontSize = fontSize,
        normal = { textColor = textColor },
        alignment = TextAnchor.UpperLeft,
        wordWrap = false
    };

   //set styling dynamically

    Color backgroundColor = new Color(...
    DrawBackground(new Rect(...
    DrawOutline(new Rect(...
    GUI.Label(new Rect(...
}```

i have to make sure to call it in an `OnGUI()` method if i forget i think my ide cries.. but it may make it all the way to the console
true owl
#

So i guess in my run method should i use the isDashing variable or something

#

to not have it override

wintry quarry
#

that's a good idea

#

and you should not call the coroutine each frame

true owl
#

why not

wintry quarry
#

because it doesn't make any sense?

true owl
#

I guess

wintry quarry
#

You will have hundreds of coroutines running at once

true owl
#

i should just call it when i actuallyt dash

wintry quarry
#

each one doing isDashing = false; every frame pretty much

wintry quarry
true owl
#

oaky

#

okey

#

thanks sorry this is my first unity project i do cs but i have no exp with unity so im a bit lost

wintry quarry
#

the whole Dash thing could just be one big coroutine tbh

autumn osprey
#

Jump Code Syntax

astral falcon
# true owl thanks sorry this is my first unity project i do cs but i have no exp with unity...

no need to say sorry, hence the name of the channel. we all begun somewhere πŸ™‚ It could also help to explain, what you expect the dash to do after its done. will the movement just continue, can you change direction while dashing and so on. You are running a lot of stuff at the same time like running overriding everything all the time, but also the coroutine, which makes sense, if you want to stop movement while dashing and so on.

true owl
#

gotcha

#

It kind works better now

#

Still have this weird issue of

#

the dash has like a cooldown

#

theoretically I should be able to spam shift and it should just spam dash

astral falcon
#

but you have the boolean canDash, no?

true owl
#

Yes

astral falcon
#

so you cant spam it

#

or can you rephrase your issue please πŸ˜„ confused over here

true owl
#

sorry 1 sec

#

okay so it seems like changing the can dash fixed it

#

sorry one more question i'm working my way through this

#

when he dashes it's kind of more like a jump?

#

he keeps the momentum, but I want it to be more of like once the dash period ends he just drops down

#

I tried adjusiting my corotuine to be kinda like this

  private IEnumerator StopDashing()
    {
        yield return new WaitForSeconds(dashingTime);
        isDashing = false;
        myRigidbody2D.linearVelocity = new Vector2(myRigidbody2D.linearVelocity.x, 0f);
    }

#

it helped a bit but seems to not be exactly what I want

astral falcon
true owl
#

why wouldn't setting my velocity.y to 0 work?

#

or wait

#

I think actually

wintry quarry
#

it does work

true owl
#

that's not the issue

#

hold on let me tweak some numbers

wintry quarry
#

also you can do myRigidbody2D.linearyVelocityY = 0;

#

to simplify the code

true owl
#

gotcha

#

it works btw

#

im dumb and numbers were bad

#

after tweaking it a bit it's better

astral falcon
#

Oh, my bad, I was not looking carefully that you set it in your code up there.

lavish radish
#

hello, I'm using this code to force a 4:3 aspect ratio on the game I'm working on
it works well on a 1920x1080 laptop screen, but I got a friend to try the game on steam deck, and the aspect ratio change did not work. The game just filled the screen.
Any idea how I could fix this?

swift crag
#

You can only enter exclusive fullscreen on Windows

astral falcon
#

as far as I know, steamdeck is 1280x800, right?

swift crag
#

yeah

astral falcon
#

and he is trying to get an int from a float

swift crag
#

ah, hm

astral falcon
#

might just not be supported to set the resolution to 4*800/3 = 1066,66666

swift crag
#

if I request fullscreen mode, it does get letterboxed properly

#

let me see what code I wrote for this...

#

I spent a while getting resolution selection behaving properly on PC, macOS, and Linux on my deck

severe onyx
#

I'm trying to get a 2d sprite to point from one gameobject to another and Im struggling to get the correct rotation to apply to the sprite's z rotation. any ideas? Ive made this work in 3d space before but that code doesnt seem to work for 2d space since it rotates the x and y values

swift crag
#
        private void UpdateWindowMode()
        {
            if (window.Chosen)
            {
                Screen.fullScreenMode = FullScreenMode.Windowed;
            }
            else if (borderlessWindow.Chosen)
            {
                Screen.fullScreenMode = FullScreenMode.FullScreenWindow;
            }
            else if (fullscreen.Chosen)
            {
                Screen.fullScreenMode = FullScreenMode.ExclusiveFullScreen;
                UpdateResolution();
            }
        }

        private void UpdateResolution()
        {
            var res = (Resolution)resolutionSetting.Value.choice;

            if (fullscreen.Chosen)
                Screen.SetResolution(res.width, res.height, FullScreenMode.ExclusiveFullScreen, res.refreshRateRatio);
        }

all of that .Chosen stuff is from my settings system

#

It's possible that I had to explicitly use FullScreenMode.ExclusiveFullScreen instead of just passing true to make it work..?

wintry quarry
#

this assumes the objects are at the same z position but if not:

Vector3 direction = target.transform.position - theObject.transform.position;
direction.z = 0;
theObject.transform.right = direction;```
severe onyx
#

oh neat ok I have the direction already anyways for placing the sprite in between the objects properly

lavish radish
swift crag
#

Well, that's what the documentation says, but it does work on my Steam Deck

#

It's probably actually doing a borderless window or something

lavish radish
#

thanks! I'll try that

true owl
#
    Vector2 moveInput;
    [Header("Movement Variables")]
    [SerializeField] float moveSpeed = 5f;
    [SerializeField] float playerSize = 5f;
    [SerializeField] float jumpSpeed = 20f;

    [Header("Components")]
    Rigidbody2D myRigidbody2D;
    Animator myAnimator;
    CapsuleCollider2D myCapsuleCollider;

    [Header("Dashing")]
    [SerializeField] private float dashingVelocity = 30f;
    [SerializeField] private float dashingTime = 0.1f;
    [SerializeField] float dashTrailTime = 0.1f;
    private bool isDashing;
    private bool canDash = true;

    [Header("Player Information")]
    private bool isGrounded = true;

    [Header("World Information")]
    private float gravityScale = 10f;
#

why are my numbers diff in the actual unity

wintry quarry
true owl
#

Can i not have it so that it auto updates with what I have in the code?

wintry quarry
wintry quarry
#

If you want to do that

#

don't serialize the field

true owl
#

how come

slender nymph
#

i just linked you to a page that explains it

wintry quarry
true owl
#

oh ok

#

i read the article

#

i just needed to reset it

#

thanks again

grand snow
severe onyx
#

will keep that in mind for the future, ty!

astral falcon
# true owl i just needed to reset it

Keep in mind, that those values are now set, so if you change your code values again, they are still override by the inspector now until you reset it again

true owl
#

gotcha

#

the dash is nicer now

#

tweaked some values its better figured out my issue with the canDash however there's still some multidash issue going on

#

Will try to fix up later

#

thanks all

west radish
#

720p for a modern day device seems really strange

rich adder
#

such a small form factor 720 is pretty good esp if you can run most games on high with decent fps

west radish
#

but phone screens are much smaller and have far higher resolution

slender nymph
#

they also do not run games nearly as high quality as the steam deck does

rich adder
#

they are running games designed for arm chips

swift hawk
#

can you find people to do projects with in this server?

eternal falconBOT
#

:loudspeaker: Collaborating and Job Posting

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

west radish
#

to be fair, the only game I've played on my phone is sudoku so I wouldnt know about phone gaming performance πŸ˜…

rich adder
#

the Go series were good, tomb raider go n such

#

iirc they were only later ported to pc

slender nymph
west radish
#

I guess the lower resolution would push it further

#

it'd be interesting to see what a steam deck looks like in person

slender nymph
#

that's also just it's built in screen's resolution. you can run higher resolutions when docked

west radish
#

honestly I didnt know you could dock it

#

makes sense though!

rich adder
#

seen few people run unity on it

astral falcon
# west radish it'd be interesting to see what a steam deck looks like in person

The steamdeck is a nice device, but I did not use it as much as I thought. But you can have some fun for controller games like souls games or nice rpgs and so on. The resolution was totally fine but it wont run high performance when docked, so higher resolutions only work for certain games. But Valve is highly working on optimising the device instead of selling a new version, which is a good thing.

umbral bough
#

Is it possible to stop being under a header in unity?
I am talking about the inspector, like can you define a header that's applied to say 4 properties and then 5th wouldn't be under it.
I am not on about custom inspectors, just wondering if it's possible.

slender nymph
#

add some space or another header. technically the header is only actually applied to the first field that the attribute is attached to, it doesn't actually do anything other than display text directly above that field

umbral bough
#

figured, so I just used a header with empty text, thanks

mental palm
#

https://paste.ofcode.org/G8MYrZGY8hrQ7x4BabKLHY

What Im trying to do is let my Player upload a list of Images into a local folder, and load these Images to the game!

I am currently trying to load a list of 2D textures from a Folder trough Unity Web Request, but it says "curl Error 37: COuldnt open file" and InvalidOperationExeption: file hasnt finished downloading"

this stuff is way over my head i just copied it from the Scripting API so any help is greatly appreciated

astral falcon
tender stag
#

cool thing i just learnt

#

if anyone doesnt know and wants to use it

#

if you have an event and want to drag and drop a script and call a method from it in the editor

#

for example a button

#

and you are passing more than 1 variable inside

#

you can just do that

steep dust
#

hey simple question is there a better way to do this? Because this doesn't feel like the correct way to do this to me.

var go = GameObject.Instantiate(examplePrefab);
var child = go.transform.Find("ExampleChild");

First thing that comes to mind is create a custom component to store a reference to the transform, but then I would just be replacing transform.Find with GetComponent<T>

wintry quarry
#

And no you don't need GetComponent

#

Example:

public MyComponent examplePrefab; // Assign to the prefab in the inspector.

void SpawnThePrefab() {
  MyComponent instance = Instantiate(examplePrefab);
  instance.DoSomething();
}```
steep dust
#

thanks

wintry quarry
polar acorn
wintry quarry
# tender stag

That top one will just cause a StackOverflowError if you call it.

tender stag
#

i click a button and it runs

wintry quarry
tender stag
#

same way it works here

wintry quarry
#

but that would definitely cause a stackoverflow

wintry quarry
tender stag
wintry quarry
#

you're calling a different override here

tender stag
steep dust
wintry quarry
#

Create() with no params is not the same as Create(null)

#

which will call a different form of the method

#

You can ctrl+click on the Create(null); and it will take you to the form it is actually calling

#

presumably uoui have some other overrides not pictured in this screenshot. It's calling one of those that matches the parameter list you gave.

#

But in the first screenshot that CreateLobby() with no params will just call itself

#

which will recurse infinitely until you get a StackOverflowError

tender stag
wintry quarry
#

Yes

#

Congratulations you've discovered abstraction

polar acorn
#

Always a great feeling when you accidentally re-invent a common programming paradigm. That's the point where you know you'll never forget how it works

ashen badger
#

Hi, random question/problem - does anybody know why it doesn't work? It should detect all dirt in radius and return the one with the richest soil. But it doesn't detect anything. Debugging isn't in english (rewritting it, for posting, would take time), but the most important thing is that it says (the first line) that "It detected 0 objects in the radius of 5 in the layer of DirtLayer". Layer ist, I think, good one; radius is enough (as shown) and it doesn't work no matter are the colliders set on isTrigger true or false. I just ran out of ideas on what could be an error or mistake (propably something simple, that I haven't noticed)

trail heart
#

Usually the best practice to write comments and logs in english as a general rule

ashen badger