#π»βcode-beginner
1 messages Β· Page 574 of 1
I thought like unity would just skip that block if it's not true, so it will move to the next
you mightve had an else if block instead of an if
it does do that
Why didn't it work?
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);
your 2 conditionals aren't exclusive, they aren't joined by an else
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
That's what IDE suggested me to do, but I didn't understand what it was used for
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
Yeah, changing it to else fixed the problem
when you check x == true, if x is true, the result is true, and if x is false, the result is false; why not skip the comparison and use x directly?
for == false, the ! logical NOT operator exists, which inverts booleans
And also, why return was a bad idea?
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
So, to not break the game and code in the future, using return is a meh idea
in this situation, yes
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.
i would not recommend separating this into more methods
it kinda is doing 1 thing, the logic can be consolidated to this
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
i have no idea what you're talking about at this point
that feature no longer exists
what feature?
The ability to explicitly disable the backCam using code that doesn't use a toggle
im so confused what you're talking about
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
so you want the code designed to enable a feature that may never exist?
code that requires... a gameobject? to be disabled?
why wouldn't that work with a toggle?
We're talking about two camera's here. The fact that it's on a gameobject is irellevant
ok, code that requires a camera to be disabled?
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
what 2 behaviors? enabling camera A vs enabling camera B?
Yes
that's just silly
it is a toggle
because you're switching between 2 cameras being exclusively active
you are wrong, under which circumstances would both cameras be inactive or active?
that is toggling between camera A and camera B
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
You're saying this like I am deliberately expecting a possible feature to be added. Instead I'm preventing code from becoming unecesarilly compact in case it ends up being extended apart from just being a toggle
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.
you are talking like a CS student rather than a professional dev
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
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'
Did the comments help you @tough plinth ? Or are you still left without a solution yet
you have a state lol, backCamEnabled
I'm sorry for interrupting, but I as Chris said to use Else If or Else in my code.
So, I actually used Else and as I got it, so if I continue my If statement with Else if, the script will check for 2nd block of code, if it's just Else it won't check the 2nd block, instead it will run it as a alternative way?
Yeah, I kinda messed with them
if it's just else, there's no condition to check, it just runs the second block if the first condition was false
Like I said, alternative way, and if Else If it will check it
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();
}
So there is no much difference between them and you should use Else If or Else depending what you want?
yeah i wasn't sure what exactly you meant by "alternative way"
ah
there is a difference in how it flows, whether it checks a conditional
but yes you should use the one that makes sense for any given task
I will think of else like a lazy way to make something xD
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
Oh and, what did you mean by "exclusive" conditionals?
Because still a bit confused of how IF and IF connectors work
(Connectors like Else and Else If)
"exclusive" means only 1 will run
The first, that is met on the else if chain will run
Yeah, as I remember people often use it just to figure out errors and find out how their values are working
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
Isn't that exactly what we have here? They had the if-else statement, and they were suggested to use the "nice" pattern that is the boolean OR that was suggested.
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
Oh, so Unity did read all that code, but executed only 1st Block, and couldn't reach 2nd because there were no Else or Else If
which one are you referring to?
My script that I used
the original one?
Yeah
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
Yeah, but 2nd didn't work due to not being checked?
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
which "2nd" are you referring to here
I refer to your logic in you message and 2nd block in my code:
https://hastebin.skyra.pw/zagihoyoqa.csharp
Sorry for being unclear
You say, is backcam enabled, then disable and then you say, is it disabled (which it is) reenable it
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
at this point just use switchπ
Not at all
There is just a thing that I worked with different language and if's can be magically connected, so it's a but hard to realize it doesn't work here D:
I still would just go for this π
backViewCamera.SetActive(!backViewCamera.activeSelf);
frontViewCamera.SetActive(!backViewCamera.activeSelf);
Sure, but they should definitely understand why the flow here has to be changed in general
pretty sure no language has this, can you be more specific
Okay, never heard of that this is the case, but I get the problem, switching if a language handles it differently. Just read it AS IS in your code. What you write, will be done , at least in this case π
I assume that even in these languages they have an else if
If they deliberately skip eachother then that would be weird
It was Lua and code worked well with IF and IF that are not connected
(OR I'm ready got super confused and can't understand something simple D: )
can I suggest you take a break? π
yeah lua doesn't do that
Lua has elseif
Ye, that's true
Just take a break and a deep breath, things will get clearer on their own
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
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
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
not in unity, in programming in general
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
The way you guys always manage to spin the simplest question into a full blown philosophical discussion will never cease to amaze me π
a full blown philosophical discussion?
there were at least 2 here
Oh, I think I got it
Prove it
You weren't expecting a pop quiz there, were you
So it enters 1st block and then instantly goes to 2nd, because it's not connected, so it's get messy
Pretty much
Omgmgkbhjjg
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
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
Ye
Running in circles π
The confusing part is that the first one changes the boolean again
So somehow it invokes the second one
I used Debug.Log and it was stuck with True, so I understand why
2nd block cannot be called because it's not connected with Else or Else-if
no...?
2nd block is called
that's the entire problem
Please just read the documentation of if statements
And change the second block to an else if, see what it changes
i think you initially misdiagnosed the problem and you've internalized it
"Beginner programming" they said 
the 2nd block is called, that's where the true comes from
An if-statement is the most beginner thing that exists
smh, hello world?
No arguments in the chat
Alright
But I think this idea of Lua doing it differently made you assume it works differently
... even though Lua works the same
oh boy π I think, the question was answered and windy can read on it on his/her own and test around to understand.
Are you sure? Maybe we need to explain it again just to make sure.
Well, with help of this chat I think I learned the lesson 
of uninstalling Lua from my pc
That's a good conclusion to take
I will take a look at the docs to figure it out, if anything, I will just re-read entire conversation, so yeah
Feel free to ask more questions on the code so we can yet another argument in here about what's best π
Anyways, Thanks for the help!!! β€οΈ@burnt vapor , @astral falcon , @naive pawn, @visual linden 
Yeah, I will, thanks again
!code
π Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
π Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
lua catching strays lol
lua has pretty normal behavior in this aspect
equivalent to bash, similar to python
just different from c-style languages
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.
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.
So what you are saying is that I also have to rotate my character controller?
I mean the transform of my player.
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.
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!
How do I insert a hexadecimal value to a color component? Idk how's the syntax here in unity
in the script
that's the neat part, you dont
what component are you talking about here exactly?
I want to change the color from global light 2d
GameObject.Find("Global Light 2D").GetComponent<Light2D>().Color = 8C0000;
i put it this way
just convert it to RGB first
either do it online or just paste the hexadecimal into a random color thing in the inspector
or just do the c# way lol
you don't need to do this
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
also this wouldn't work
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
rgb isn't really a datatype
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
huh, the more you know π
cursedly, you could do new(0x8C, 0x00, 0x00) / 0xff (you shouldn't)
@cerulean badger
you could also use floats directly, new(0.55f, 0f, 0f)
you could also write the constructor in full, new Color(...)
since the color is constant anyway. have you tried doing
public Color lightColour;
(example image is a bit messy, i just shoved this into another script with a bunch of other stuff
)
mmm yes i think im looking at the wrong docs
Considering nobody mentioned it, this will work when you wrap 8C0000 with this method: https://docs.unity3d.com/ScriptReference/ColorUtility.TryParseHtmlString.html
Just put a # before it or it will not be valid
And please consider making a static instance out of it or something if you ever plan to change it on runtime.
oh yeah, i keep forgetting that exists
GameObject.Find("Global Light 2D").GetComponent<Light2D>().Color = new(0x8C/255f, 0x00/255f, 0x00/255f);
is this correct?
My eyes!! π
static instance
...you sure about this?
Please just use [this](#π»βcode-beginner message)
are you suggesting a singleton
Yes, because it is a global light, sounds to me it should be there always and changed probably dynamically
if (ColorUtility.TryParseHtmlString("#8C0000", out var color)
{
GameObject.Find("Global Light 2D").GetComponent<Light2D>().Color = color;
}
I'm not understanding a single word from this
See code example
no, i mean you sure about the words there?
do you mean a singleton
you sure .Color exists?
Maybe in your case log a warning if the parse failed
this heck of a giant code??
Yes, singleton so you could access the light through any script from anywhere
No. π«΄ #π»βcode-beginner message
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
is there any reason why you're using hexadecimal in the first place?
actually not lol
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"
you might want to consider making a field of type Color instead to be set in the inspector
idk what a singleton is
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?)
im pretty sure this is still the simplest method
yea i dont need, it may be any color format, since it works
then take jordands suggestion, just use a Color property
and read https://docs.unity3d.com/Packages/com.unity.render-pipelines.universal@17.0/api/UnityEngine.Rendering.Universal.Light2D.html#UnityEngine_Rendering_Universal_Light2D_color , as chris stated, its not .Color with uppercase but lower
- public Color lightColour;
+ [SerializeField] private Color _lightColour;
im taking this
here we go with those mumbo jumbo again
If that confuses you I strongly suggest you take basic Unity lessons. SerializeField is a very common attribute to use
I suspect it's the diff formatting that's confusing to someone not used to reading it
in most cases you'd want to do what FusedQ said. i just used public in my example since its the same thing (for a beginner atleast)
yea ik that but I intend to deal with only a thing at once, but SerializeField is at the top of my queue of things to learn
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.
so it allows me to make a private variable that still shows up in inspector and other scripts?
Well, not other scripts
oh, easier than I expected lol
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
The point is avoiding access from other scripts
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
hmm got it
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
that's why I'm the music guy and not coder 
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.
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?
imo it could be either ur idea of multiplying or checking if arm control input is being used
I will try both
when does code in different scripts run, relative to each other? same frame?
Depends which code
"scripts" is a bit of a vague term here
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.
i dont know. but, you can make them run at a seperate time by adding the script here
The diagram here might help you understand: https://docs.unity3d.com/6000.0/Documentation/Manual/execution-order.html
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
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?
Use a for loop
(notably, you'd need to use a for loop to be able to assign the result back into the list)
for (int i = 0; i < myList.Count; i++) {
myList[i] = myList[i] * 3;
}```
foreach would not permit you to change the contents of the list
The easiest way would be with Linq and Select, if you know what that is
myList = myList.Select(x => x * 3).ToArray()
do you mean something like "if 3 scripts have code that runs on update, which one runs first?"
(there is a ToList method)
that'll at least prevent you from allocating twice as much garbage as needed
Notably Linq will create a whole new list which isn't good for performance.
Ah yes, I didn't notice they mentioned it was a list
Yeah I do not understand anything that weas just said to me (first time using lists)
Well yeah, I meant easiest, not least allocation
If you have no clue what anything we just said means, you need to learn how C# works
!learn
:teacher: Unity Learn β
Over 750 hours of free live and on-demand learning content for all levels of experience!
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
LINQ is a leap in its own way, of course
literacy with basic for loops should be encouraged π
you're introducing anonymous functions
Could I put that in an IEnumerator?
you can put it wherever you want guy
Yeah, this does assume that you have knowledge of LINQ
Thanks
Also it's called a coroutine
Hard to say what experience each person as ofc
Anyone know why my mesh collider is completely off even though i've provided it a mesh that is correct?
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.
It's not on the same object as the MeshRenderer.
not a coding question
It's also marked Convex
- You marked it convex
- This object is a different object than the one with the renderer and has its own independent dynamic Rigidbody which will move freely
- This isn't a code question
Well cheers for the help anyway π
all i needed, thank you
im actually kind of curious about this myself. i dont know which order code gets executed in when it's in different scripts (or events in this case)
If you subscribe ten functions to an event, the functions will run one at a time.
They don't all execute "simultaneously"
if you need to enforce a specific order of event handlers running, you should use a list of delegates, rather than a regular event, and put the delegates in the list in the correct order.
Similarly, Update methods don't run "all at once"
they run one at a time, in some arbitrary order
tysm; does that mean then, that putting a coroutine in one will not actually delay the running of the script for "long enough" that the other script can run? because if not then my only solution other than i guess a list of delegates like praetorblue suggested is gone
ill try it anyway but this is interesting thank you
Coroutines cannot and do not delay the code that starts the coroutine
That would freeze the game!
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
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.
It sounds to me like they just have an order-of-operations problem that they're trying to fix with a delay
Sounds to me like they think an event listener that starts a coroutine will itself wait for the coroutine to complete
that too
(which you should avoid at all costs)
We're just speculating though
indeed
But we can answer their question and explain how they delay their execution and let them figure the rest out as they go.
You can set execution order of update methods through project settings or with the [DefaultExecutionOrder] class attribute
Unless I'm misunderstanding the question
I'd rather take the time to figure out the actual problem and come up with a proper solution
This all has the strong feeling of an XY problem to me!
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
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 :)
The mouse click should do nothing but ask the camera to take a photo.
- 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.
- 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?
If the camera says "yes", then it should go and run some other code.
I see we're jumping at the chance to do a code review π
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
Yes, because we're trying to work out the root cause of mack's problem
We could try to find the absolutely simplest way to fix the current issue, yes, but that wouldn't be helpful
to both points, im very new with the event thing as a whole and still trying to learn it so i am still not fully educated on what exactly that fully means, if it seems illogical to do its probably because it is and ive misunderstood lol
the C# documentation makes it sound like EventArgs is some kind of magical type you have to use with the event keyword
what? EventArgs is just a class like any other, nothing special about it at all
also, importantly, you haven't separated the "logic" from the "visuals" here -- notice how CameraClick is responsible for resetting logic.busy!
youre very correct
I see what you mean, the typical over complicated bullshit explanation
i think this literally fixes it from the beginning
so you'd have something closer to this
[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
```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
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
In this case, though, displaying the photo on the screen is pretty integral to how your game's camera works
I would perhaps spin up a coroutine to avoid the mostly idling update loop
perhaps, but using a coroutine results in garbage, so it's a bit of a wash
perhaps you might be interested in this article:
https://gameprogrammingpatterns.com/observer.html
not recommending that you use events, but just as a resource to understand them
I use events any time I want to react to something happening, like an entity being destroyed or a setting being changed
Does it? You can cache the WaitForSeconds and avoid that allocation, but it's true I don't know if StartCoroutine allocates.
An enumerator method is translated into a class by the compiler
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
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)
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
I dunno, looks more like a wolf, or maybe a panther?
clearly a bnuuy 
looks like hyena 
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
The bool you're expecting to set is xExist?
Yep
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
I am aware of the Random.Range thing i just set it to let me spawn it more often
Is it not suppossed to be a float?
Well, it can roll any value between 1 and 2, which means it'll basically never be exactly 2
ohh so it can roll decimals too?
That's what a float is
(only for ints)
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
Flot makes it possible to get 1.35683 coin
Yep ik
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
First off, try logging the bool after you set it. See if that code runs
I canβt view the entire script on my phone lol
After switching the random range to have an f it started giving decimals, so it was fine before that
not if you only give it ints
when in doubt, refer to the docs: https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Random.Range.html
logs show it switched to true but on the prefab it's still false
Are you setting it on the prefab?
Cause inspector settings overrides public varibles
Its being set on the button that has spawned
(Instantiate)
Okay, so that one will have it's xExist set
Look at that one
It gets destroyed on click
Then there's not much point in setting a variable on it
How else could I make it true when rolling the 3x?
If you want the data to persist after this object is destroyed, something else is going to need to hold that data
Every single instance of this BigMoney script is going to have its own xExist boolean
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
The one on the prefab, the one you spawn in, any other copies, etc.
Ohh that makes sense now
So, since this object ceases to be, then nothing holds that data
So just make the bool in a different script?
And then set it to true via BingMoney
Yes, have the button tell that script to change whatever boolean
You could
Will give that a shot
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
Isn't the list capped at 4 though?
mults = new List<float>(4);
that's the point of lists over arrays
That creates a list that has four zeroes in it to start
Then you add four more things to it every physics step
Oh I thought that was the capπ
And about the get component one, how else would I access the variable via prefab?
Change FixedUpdate to Start
You'd call GetComponent one time and store the value in a variable
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
Thanks
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
Thanks yall that worked! But 1 thing is that my multipliers aren't 3x anymore whenever i get the multiplier https://paste.ofcode.org/YQVYkr3gDhJUfk3ghq5UyY
List doesn't , i think its about 2 million entries before you hit limit
Actually, no!
It just makes the list start with a certain capacity
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
Ah, I figured it created a list of that length, which would populate with default
π β The More You Know
mains.GetComponent<MainScript>().acm = but.GetComponent<BigMoney>().mults[0];
Youshould cache these @frigid sapphire
wrong reply srry lol
Oh youre right same mistake as last time with the getcomponents
how are you verifying the values ?
which one is supposed to change ?
also you should really be using arrays when you have such variables numbered
are you certain the function runs, the only thing you have to verify besides inspector is xt.text = $"3x Active! {Mathf.Round(timero2)}s left";
also kinda strange this is FixedUpdate insead of update
Yes timer is going down
also starting a new coroutine every physics frame seems like a recipe for disaster
Will move that to start now
dont you have a specific method / time you want to call the function instead
or its just timer based ?
Well it's suppossed to be running at all times, spawns like a golden waffle every set time
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
Maybe just put a while loop in the coroutine?
Your game might freeze
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
True, if it's within the while loop
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
also would print but.GetComponent<BigMoney>().mults.Count
Well that seemed to give a big clue, It's 0
closer to the answer π€Ί
debugging and its power
if its 0 its not running a for loop, because looping over 0 is no loop lol
0 != 0 < 0
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; }
i bit cleaner, I would advise you would not use abbreviations though. make your varibles and classes CLEAR on whay they are and what they do
did you figure out why it was 0 ?
Nope I have no clue yet
Cause it's clearly suppossed to add 4 things to the list but it's not??
are you certain that Start is running ?
Debug.Log("Is start running"); and got nothing lol
did I actually manage to misspell Start
no, you just did not attach this script to a gameobject
is this gameobject active and enabled ?
It's a prefab
Yeah every 1-2 mins
Could there be some exception thrown in the Console halting the execution?
A bunch of 0s
also make sure the messages are not collapsed
ypu are spawning a button every 1-2 minutes?
also this ^
Yep it's like a golden waffle that gives you a 3x mult or some cash
why not just enable and disable the same one instead of instantiating a new one
Good question, I have no aswer for it tho
you still haven't answered #π»βcode-beginner message
Its in the assets should be active tho, everything worked before I moved the List part into Start
It was in update before
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.
wdym "in the assets"
also if Update ran, Stat most certainly ran
the script doent run unless its on a gameobject in the scene and active
How did update work then?
Ohhhh cause it was in update the list got created when it spawned?
π€
I will move it back to update and check
that's just nonsense, Start will run on the instantiated object
wait. THe debug part is most important here
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
Everything else is running
oh wait huh my timer has just stopped going down
oh right yield return null disregard that
show the updated script
I can give all 3
script inside button https://paste.ofcode.org/75emXdisdtJQdH4XhWkZJf
golden waffle controller https://paste.ofcode.org/32SGqk3Sbw6dewLt2DCw55g
actually i'll just give the 2 cause main script has like 460 lines
where is the debug log
Deleted now
why..you are still debugging
I am yeah
Well while loop decided to freeze unity, hope i made a saveπ―οΈ π
where is the while loop. the script you sent doesnt have any
Second script
second link
It's a gnarly loop and I saw how far indented it was and thought "I aint reading all that"
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
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
It was calling the coroutine every tick but I decided to just put it in a while loop
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
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
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
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
Yeah this is pure improvising
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
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
show UPDATED scripts
https://paste.ofcode.org/JyVq7wXC6ypE55tQqYHaAA gold waffle controller
https://paste.ofcode.org/bfCi9X6fzSbbkLbDUK5kM button script
https://paste.ofcode.org/LH2weRWCth4JyeyGRGf2Ym longest and least clean script of the project (even if you give me hundreds of tips I ain't changing this up too much workπ―οΈ )
so which one is not applying 3x
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
void FixedUpdate()
{
mults.Add(ms.acm);
mults.Add(ms.mult);
mults.Add(ms.p4m);
mults.Add(ms.p5m);
}```
jesus..
you reaalize this is adding 4 entries to your list every physics frame
Yep it was in start first but nothing happened so moved it to update to see if it'll work
i should point out that these are very bad names
I can't tell what this is meant to do
that's the new playstation product, obviously smh
yeah I suggest this to OP earlier, legibility is more important than working code
(playstation 4 mobile & playstation 5 mobile)
well instead you should Log start and find out WHY thats not running. Dont make a solution by creating another problem
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
if even you don't know what these things mean, then you have a serious problem
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
It was being logged in start Debug.Log("Is start running") and nothing popped up
a lot of these problems would literally be solved by just learning arrays lol
Are you expecting the multipliers in this list to stay up-to-date as the values of ms.acm, ms.mult, etc. change?
Yep
yes that means you have a bigger issue to solve first
They will not. The list stores copies of those values
float is a value type; it is always copied and never shared
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?
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
Omg I thought "i" was everything in the list
...no
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
:teacher: Unity Learn β
Over 750 hours of free live and on-demand learning content for all levels of experience!
You're going to have a much better experience if you aren't stumbling around in the dark
yes having more tools (code / functions) are your disposal will yield better code
you could (but absolutely should not, this is a joke) make mults a Vector4 and do bm.mults *= 3;
π

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
Will educate myself, just wanna finish this golden waffle thing thats been annoying me for the past 2 days
How could I multiply all the contents of a list?
that weird tho I did that at the start and it worked but now it just stopped multiplying it
how do i change the direction of gravity here
-gravityVariable
You can change gravity by modifying Physics.gravity
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
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
ok because i was trying to get gravity to be towards an object
Get the direction from A to B with:
Vector3 direction = (B - A).normalized;```
set the gravity with Physics.gravity = myNewGravityVector;
yeah but also things like the jump and "extra gravity" in the movement code confuses me
That code, to be perfectly honest, has a lot of problems with it
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
it is a dani project.. π€ͺ
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
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
im pretty sure not even he doesnt knows how it work
!code
im almost 50% sure theres some code in his game he copy and pasted w/o any knowledge of it yea
π Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
π Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Doesn't sound like a good basis for writing your own game scripts then, unless you don't really care that much about it and just want to make a throwaway project.
ive even seen sections of his tutorials where he "yoinks" code from online
and just moves along
i just want something that works
is it close?
it works as long as you dont want to edit
if u just want something that works
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
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
oof, u should be trying to get away from that.. modularity is key
u should be able to swap out controllers on the fly w/ little to no breakage..
thats part of the S in the SOLID principles:
https://unity.com/resources/design-patterns-solid-ebook
but ur original question has been answered.. soo imma leave it at that π good luck mate
i could swap the controller but the game would just feel extremly boring
like taking the portals out of portal
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
like so:
can pause the game.. completely remove my player.. and drop in a new one.. and carry on
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
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
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);
}
As said, its returning a float, because you set the input asset to output float and not vector 2
i dont know a whole lot about the new input system.. but ive seen similar errors elsewhere..
seems like ^ that is ur issue
A Vector2 control type is going to need more than just a button to define it
you say, dash is vector2, but pressing a key is never a vector2 because pushing is only one axis
think about it
It contains two values, X and Y. Shift is only going to give you one of those
WASD works b/c theres (2) keys tied to the single value
a positive and a negative
I want to contain the direction of the dash though, one of 8 directions
you just want to activate the dash, right? The direction should (most likely) be in the direction you are facing with your character
u can do that by reading ur direction
Ah, so you want to activate like a target system?
I guess kind of? I want it so if I'm holding W+D it'll go to top right for example
or where do the players decide on those 8 directions?
so, its in the direction of your player
but clamped to 45 degrees movement
yeah
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
Which you get from your existing movement keys
and then check if you're pressing the dash button
ah
You just gotta project your vector2 to the 360 radius and step it to 45 , there you go with your direction
interesting
Of course, oversimplified, but thats what you tell the code to do in the end π
Remember - it's an input map. You're binding to buttons. Having a "Dash stick" doesn't really make sense
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
You would normally press a dash button, and dash in the direction of the movement stick
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
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
if ur player is already facing the direction u tend to dash.. u could just use the transform.forward
but thats just an assumption
dang
this is rough
Alright
I have a moveInput already from my onMove, so I'll try using that I think
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.
first thing I see is, that you run your coroutine every fixed step when you get the key
your while loop doesn't have any yield inside it
therefore the entire loop will run within a single frame
What twentacle said is also a problem
shouldn't it stop after the first one because isGrounded will be false, or am I misunderstanding how that works?
ah true, if thats the case that its not grounded within the next step
this makes a lot of sense tragically π
but Jump should be running on its own, as its a coroutine
Or am I missing something here π
it is definitely me, not you lol. i've been a little lost trying to get the hang of scripting again and i'm definitely messing up certain portions
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
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
Nice, good attitude, see you around π
should be the first thing u write π
even after 3 years i still use them for everything
I want to figure out a better way to categorize my log statements
same.. π¦
ideally I'd have a hierarchy of them that I can toggle
even after color and formatting i still would rather have a better way..
ooh, wait, I have an idea
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
u thought about using on-screen loggers?
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
I have some of that
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
mine uses Dbug.Log
omg, you're a streaming service? (ref)
that feels so cursed lmao
but not so much intuitive enuff for me
too clever
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
noooice
is it GetType().Name.GetHashCode() % 0x1000000?
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
do you exclude the execution from the stacktrace?
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
hang on i was just about to mention the stacktrace
then i will just use breakpoints for most
But will stop immediately on device tests sadly
can breakpoint on devices just fine
do it all the time for console and mobile
yeh, my experience is on AVP last couple months π
also it does not need to stop
the only thing i haven't fixed w/ mine is a way to go directly to the instance that calls the method
i can have the breakpoint just log
so i have to go to the bottom of the trace π
But excluding the stacktrace will still open the logger when double click, right?
Oh no. I just finished hemming and hawwing about another problem
Now I'm thinking about this again

this week's dev log: have you guys ever heard about bikesheds?
ya, i pass in context
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
Oh wait, my bad. you still use the debug.log from Unity. I am actually overriding the whole thing π
oh no.. yea.. mines jsut a cheeky little redirect
lol
ur more advanced than me clearly
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.
your movement code is not compatible with this no doubt.
You are probably setting the velocity directly in the movement code, which means it will overwrite whatever velocity you set in this dash code.
That's my guess
I also have in my update method this coroutine StartCoroutine("StopDashing");
oh nice, i just googled randomly for it and found a solution to it, its just a unity assembly thing, Noice! π
There is no coroutine in the code you just shared so this doesn't mean much to us
Sorry about that
{
yield return new WaitForSeconds(dashingTime);
isDashing = false;
}```
this is the coroutine
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
From my understanding I thought this would kind of stop all other movement of the player until that time frame ends?
only if your "other movement code" is aware of this isDashing variable and does something with it
You haven't shared it so we can only guess
It would probably be simpler to just share the full script
!code
π Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
π Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
oh gotcha
A tool for sharing your source code with the world!
thanks for the help in advance
myRigidbody2D.linearVelocity = new Vector2(moveInput.x * moveSpeed, myRigidbody2D.linearVelocity.y); ;```
your code is doing this every frame
the dashing stuff is going to be completely overwritten
and this too
yeah starting the coroutine every frame is absolutely wrong
Woops, huge pasted image, sorry
i see
so how would I go about fixing this, shouldn't run be called every frame?
and your movement code will need to care about the isDashing variable for the dashing not to be overwritten
SHouldn't you NOT do the Run code if you're currently dashing?
Should I just not do a method called run and have a huge movement method instead or
that's a structural question that has little to do with the actual problem
I guess
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
So i guess in my run method should i use the isDashing variable or something
to not have it override
yes
that's a good idea
and you should not call the coroutine each frame
why not
because it doesn't make any sense?
I guess
You will have hundreds of coroutines running at once
i should just call it when i actuallyt dash
each one doing isDashing = false; every frame pretty much
yes that would make sense
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
the whole Dash thing could just be one big coroutine tbh
Jump Code Syntax
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.
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
but you have the boolean canDash, no?
Yes
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
when the dash is done, you can reduce the velocity with multiplying something below 1 until you reached your desired defaultspeed
it does work
gotcha
it works btw
im dumb and numbers were bad
after tweaking it a bit it's better
Oh, my bad, I was not looking carefully that you set it in your code up there.
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?
You can only enter exclusive fullscreen on Windows
as far as I know, steamdeck is 1280x800, right?
yeah
and he is trying to get an int from a float
ah, hm
might just not be supported to set the resolution to 4*800/3 = 1066,66666
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
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
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..?
You're almost certainly overcomplicating it:
Vector3 direction = target.transform.position - theObject.transform.position;
theObject.transform.right = direction;```
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;```
oh neat ok I have the direction already anyways for placing the sprite in between the objects properly
I see thank you, you did say exclusive fullscreen only worked on windows, right? So would this work for other OS ?
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
thanks! I'll try that
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
Because they were already saved with those values
Can i not have it so that it auto updates with what I have in the code?
Basically the entire point of having an inspector is to allow the scene to save different values for those fields than the ones defined in your code. Otherwise it wouldn't be possible to have two different objects with different data on them
that would be a terrible idea
If you want to do that
don't serialize the field
how come
i just linked you to a page that explains it
Because the point of the inspector is to be able to set the values in the inspector
The other way you get a rotation for a 2d dir is Mathf Atan2
will keep that in mind for the future, ty!
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
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
the steam deck isnt even 1080p?
720p for a modern day device seems really strange
such a small form factor 720 is pretty good esp if you can run most games on high with decent fps
but phone screens are much smaller and have far higher resolution
they also do not run games nearly as high quality as the steam deck does
they are running games designed for arm chips
can you find people to do projects with in this server?
!collab
: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
to be fair, the only game I've played on my phone is sudoku so I wouldnt know about phone gaming performance π
the Go series were good, tomb raider go n such
iirc they were only later ported to pc
well you're certainly not going to run elden ring on your phone, but you could on a steam deck
I guess the lower resolution would push it further
it'd be interesting to see what a steam deck looks like in person
that's also just it's built in screen's resolution. you can run higher resolutions when docked
seen few people run unity on it
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.
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.
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
figured, so I just used a header with empty text, thanks
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
where does this error occur, what line of your pasted code
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
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>
It's better to create the custom component but not to expose a reference, simply expose a function that does what you want to do
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();
}```
didn't even think about doing that wasn't aware you could spawn in a prefab from a component reference
thanks
It's the only way you should do it, 95% of the time
Yes. It still makes the entire object, it just returns the reference you specify
That top one will just cause a StackOverflowError if you call it.
somehow it doesnt
i click a button and it runs
I meanm there's no code here to run tbh
same way it works here
but that would definitely cause a stackoverflow
this is different
i can assign the Create to an event in the editor
you're calling a different override here
wdym by that
you're passing null as a parameter to the create method
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
so i can do this?
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
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)
OverlapSphere detects 3D colliders
Physics2D.OverlapCircle detects 2D colliders
Usually the best practice to write comments and logs in english as a general rule
Okay, Thanks for solving this. Problem as simple and unnoticed as I've expected