#💻┃code-beginner
1 messages · Page 355 of 1
ok so Invoke is not running ?
Hello everyone, I have a problem with my character, when I land from a jump, the player go into the ground and after tp himself on the ground to the right place... Can someone help me ?
now it's running fixed it
but the seconds doesn't add
when obstacle respawns
why not?
show movement scripts, also try turning collision to continuous
are you adding it to the variable that ur printing out?
I'm using prefab to create so map so I don't think it's possible
you can edit prefabs
also what does map have to do with character's collider
they're just a collection of gameobjects if u double click a prefab it opens it in the prefab editor window
shows all pieces of it
I tried RotateTowards as well as the improved Lerp from the page you linked.
They give the same result as what I've been using.
I appreciate the help, though.
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To 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.
Without seeing what you tried it's hard to say why. I do have to step out so one thing I recommend is to add a few debug DrawRay's to see where it's even trying to look. Possibly a green line for the desired look direction and red one for the current direction
This is an interesting way to describe it. Kind of insightful with the concise phrasing
the code works fine.. you only have 1 timer variable that you can print out
it threw me off at first.. b/c it was counting super slow.. and then i saw ur .05f seconds variable..
changed that back to 1 so it counts in seconds again
At least one other person on this server appreciates correct spelling, grammar and the ability to articulate, thank you
i think i need to rename thoose
maybe it would work
it doesn't matter what u name it
did u use my scripts?
b/c ur giving it the Text gameobject's reference
https://www.spawncampgames.com/paste/?serve=code_401
a version of it yes
dam for me it some how the script doesn't work when i was creating with score it worked when the obstacle respawned it gived me a score +1 but now with this timer it doesn't add seconds
the script i copied didn't even have a method to add time to it..
u add the time by gui
so i'v followed the tutorial of unity, now i know what variables/methods/ all the things are but now i dont know what to do? is there some sort of lineair path i need to follow? or do i now have to have a small concept of a simple game in my mind and research it how i can make it and everyline of code i see that i dont understand or dont know i just start researching about that and how it works? or is there indeed a lineair path?
How do I change these values in code? (figured it out. offsetmin/max)
I'd say pick an easy-ish project (you can consult folks here to make sure you're not being overly ambitious) and then try to build it
You don't know what you don't know, and much of that gets picked up as you go
Yo
maybe these are problem why they don't work
Kill the character if he touch a monster / a spike
where can I turn the collision to continuous ?
I'll tell you one thing - you should not be multiplying Time.fixedDeltaTime into your velocity
fixing that will make your moveSpeed numbers make sense
but won't fix anything else
specifically here: rb.velocity = new Vector2(direction * moveSpeed * Time.fixedDeltaTime, rb.velocity.y);
what should i put instead ?
what does this mean
it means exactly what it says. you do not have an input button called "jump" set up in the input manager settings
You wrote somewhere something like Input.GetButton("jump") but never created an axis called "jump".
By default there's one called "Jump", maybe you meant to use that?
what do u mean
"Jump" and "jump" are not the same
system.buffer.blockcopy is able to create any variable from just bytes?
i got a character animated, when the character attacks, an attack curve is appearing in its base sprite. what's the best way i can do to manage the attack connection with other object? i did using the Raycast method which is rotating by frame to adjust the melee curve, is there another better way ?
!vs
If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
YES
It doesn't create anything, it copies data from an existing array to another. The array must contain primitive types (int, long, byte, float, etc.)
aw
maybe there something else that can create non primitives out of bytes
i searched for such thing for years
Well, if you have your own data type you want to read and write as bytes, you need to do that manually
There's BinaryReader and BinaryWriter that allow you to read and write data from/to an underlying Stream
something to check out in future
meanwhile
i made my own site server which serves me big strings with all data at once
but i noticed issue with mp3 files where 5mb file turns 75mb
because i have to provide float array to create audioclip
which is huge
go home compression algorithm, you're drunk 🍺
any kind of compressing resulted in white noise from audio clip
static helper classes are coooool..
Went from: cs targetDir = local ? ( direction == Direction.North ? targetObj.transform.forward : direction == Direction.West ? -targetObj.transform.right : direction == Direction.South ? -targetObj.transform.forward : direction == Direction.East ? targetObj.transform.right : direction == Direction.Up ? targetObj.transform.up : -targetObj.transform.up ) : ( direction == Direction.North ? Vector3.forward : direction == Direction.West ? -Vector3.right : direction == Direction.South ? -Vector3.forward : direction == Direction.East ? Vector3.right : direction == Direction.Up ? Vector3.up : -Vector3.up ); to: ```cs
if (local)
targetDir = Utils.GetDirection(direction, this.transform);
else
targetDir = Utils.GetDirection(direction);
#💻┃code-beginner message
Finally did something about it 😄
might be more intuitive what its doing if you use extension methods
public static Vector3 GetLocalDirection(this Direction direction, transform)...
public static Vector3 GetWorldDirection(this Direction direction)...
ya, im working my way up to those.. 🧡
they just intimidate me r/n for some unknown reason
how could I make wall jumping for my 3d game?
Literally just a function whose first parameter has this in front of it
Which is the type you want to add a function to
its very easy, and then you can also do
targetDir = direction.GetWorldDirection();
whats the proper way to implement extension methods..
would i put it in a static class?
just a class with this for the method declaration
oh, okay.. I've only done it once.. with Debug for 🌈
and that made me even more confused tbh..
because i named my static class as Debug.. and it wasn't in a namespace or anything
and unity would automatically let me call Debug.Log() from my own class without ever complaining that it wasn't UnityEngine's Debug
oh sorry i confused myself, yea it has to be in a static class too
ever since then i was weary.. b/c of the naming.. was scared of confusing the IDE and getting the using statements all mixed up
imma try em out. again when i find a free-spot.. i'd like to extend Debug again, only this time to utilize GUI handles and stuff
#region Input / Debugging
/// <summary>
/// Display text on the screen in real-time for debugging purposes.
/// </summary>
/// <param name="text">The text to display.</param>
/// <param name="position">The position of the text on the screen.</param>
/// <param name="size">The size of the text.</param>
/// <param name="textColor">The color of the text.</param>
public static void RealtimeDebug(string text, Vector2 position, Vector2 size, Color textColor)
{
GUIStyle style = new GUIStyle(GUI.skin.label);
style.normal.textColor = textColor;
Rect rect = new Rect(position.x, position.y, size.x, size.y);
GUI.Label(rect, text, style);
}
#endregion``` something as such
atm i just have an empty static class called Utils that im using basically as a container i guess i'd call it
if it were me, i'd probably use a https://docs.unity3d.com/ScriptReference/Physics.OverlapSphere.html somewhere on the player and find a way to distinguish my walls from other colliders
use it similar to a groundcheck paired with jumping
if (canWallJump && Input.GetKeyDown(KeyCode.Space))
{
PerformWallJump();
}``` where canWallJump would be true if your notGrounded + close enough to a wall + perhaps checking if we're falling (if u wouldn't want to wall jump on the way up from a normal jump)
do audio samples have to be in pcm or can be some more sane format?
how can i set a definition for left?
negative right
Oh, actually, Vector3 does have left
It doesn't have Left though
don't got what
get it *
I believe I have tried everyone's suggestions for how to fix this. I have commented out, in the code below, what I have tried that was not in my original code.
I've recently added debugging rays (thanks to @eternal needle for this suggestion) and sidestepped the slerp all-together to see what would happen if I just snapped the player's rotation to the target rotation. The issue still happens (jitter) and it looks like the red rays, representing current rotation, are lagging behind the green rays, representing target rotation. I'm not sure why this is happening... I set up a similar code in another project and the green & red rays line up exactly on one another. I cannot pinpoint the difference between these two projects and don't exactly know what this behavior hints at.
If anyone has any ideas I would greatly appreciate it. It looks like what I've seen people online complain about when their rigidbody/physics stuff is called in update instead of fixed update, but I am calling the rotation function in fixed update so I'm at a loss.
Link to code: https://gdl.space/ikuzuhehat.cpp
For context; My other project I worked on before this that used an identical method to do player rotation would get me results such as in this video. (The green and red rays representing target rotation and current rotation are lining up on top of another without any delay or jitter)
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To 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.
https://gdl.space/revunevepe.cs
How do I check if the player has collided with the onPlatformCollider
I am doing the Create with Code course by unity and I just added SpawnEnemyWave() however every time I play the game it freezes my pc. anyone know how to fix this?
So the resolution is really hard to read, but you have 1 - i++ in the for loop?
That will make an infinite loop
Thank you that fixed it
Ah ok. Glad it worked
OnCollisionEnter or Physics query
OnCollision or onTrigger?
depends how you intent to use this
Just as a trigger
so use OnTrigger
Yeah so I used the collider.tag and it returned untagged
Even tho the play is colliding with the collider
is the collider have a tag?
show current code you wrote
I just realized tag and game object name are two different things
yes.
and you for sure dont want to use names
I always thought they were the same
tags are a finite source
Why?
may need them for sum'n else
if u do use tags use CompareTag("YourTag");
and not if .tag ==
because is diffcult to tell if you spelled something correct for one
no intellisense for strings
and gameobject names change, or if they do everything breaks.
Nah this isn’t the problem I just realized my player doesn’t have a tag
I didn’t know you’re meant to tag game objects
Makes sense
yeah tags are ok. I just personally would rather use a component
since unity is component based its perfect
Wdym?
like if you do
if(other.collider == someOtherCollider)
thats component
but ideally you would try to find one like a tag not compare
You mean the player collider in my case?
No i just meant components in general
Transform, Collider etc..
they're all components
i like cs private void OnTriggerEnter(Collider other) { if(other.TryGetComponent(out EnemyHealth enemyHealth)) { enemyHealth.health -= damageAmount; } } trygets
I mean the someOtherCollider for me would be the player collider?
lol.. my tag system
if(other.TryGetComponent(out BlueScript blue))
{
//Make Blue Do();
}```
na forget what I wrote on that
it was just a random example
from your script
u could compare ur players collider if u wanted to
It says rb velocity is 0, 0 but it's moving
You're moving the transform.position using Vector3.MoveTowards; you're not actually moving the rigidbody
What problem are you trying to solve?
rb.velocity is indeed zero, and your character is moving properly. Are you trying to measure something?
I wanna use the platform velocity to move the character
When they’re in a platform I mean
When they're in a platform?
Is there another way I can do this?
hey
That code snippet is for moving platforms
So if a platform is moving below them, you want the player to be moved in the same direction as the platform?
Ah, I see
Exactly
I was working on a sort of timer for my dash, and I forgor how to use time
https://hastebin.com/share/uxozoxawiy.csharp
this is what I was doing tho
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
There doesn't seem to be an intuitive way to do this using physics, so I would use OnTriggerEnter and OnTriggerExit to detect player collision and move them manually
Ts is so much easier on Pygame
Manually in what sense?
pygame?
The python module for game dev
Player touches platform -> Platform registers OnTriggerEnter -> Platform does math to determine which way the player needs to be pushed -> Pushes player rigidbody until OnTriggerExit
Actually
Yeah that’s what I wanted to do
First, try Rb.MovePosition(transform.position + direction * speed * Time.deltaTime)
just use a coroutine and a bool
I'm not sure if rigidbody.move handles physics interactions in the way that you're hoping for, but it does interact more with the physics.
I’d try this tomorrow, it’s 2am and I’ve been coding all day
Thanks so much tho
No problem! I recommend reading Rigidbody documentation on Unity and scanning for built-in methods that might seem useful to you
For sure, I’d try that
Also, I can’t attach the platform game object to the player prefab
Is this normal or am I missing something
I seen that a few times, how do I use a coroutine tho?
like a normal method but instead of void its IEnumerator, inside you make it true/false then yield return new WaitForSeconds(1f); then make it true/false again
Official docs are great
https://docs.unity3d.com/ScriptReference/MonoBehaviour.StartCoroutine.html
Okay. I've updated the code and once I have the player rotation snapping to the target rotation using transform.rotation it seems to behave like my code in my other project did where the target rotation and player rotation are in sync when the camera is turning.
With the DebugRays (green for target, red for player rotation) now lining up on top of each other I would not expect any jitter, but it still exists... Really not sure why this is the case. Linking the code below and a video of what I am encountering.
so, uh, I was reading and the yield didnt really click
what does yield do?
it waits based on the amount of time you provide or the condition . . .
Yield provides the next value in an iteration
then it returns to that same spot after the time expires . . .
What do you mean?
oh
thanks
I don't think their explanation was correct
i dunno
Read the official documentation
it made sense for me
It made sense because it's simple and wrong
Please read the official docs.
If you have questions about the official docs, ask a tailored question
var numbers = ProduceEvenNumbers(5);
Console.WriteLine("Caller: about to iterate.");
foreach (int i in numbers)
{
Console.WriteLine($"Caller: {i}");
}
IEnumerable<int> ProduceEvenNumbers(int upto)
{
Console.WriteLine("Iterator: start.");
for (int i = 0; i <= upto; i += 2)
{
Console.WriteLine($"Iterator: about to yield {i}");
yield return i;
Console.WriteLine($"Iterator: yielded {i}");
}
Console.WriteLine("Iterator: end.");
}
// Output:
// Caller: about to iterate.
// Iterator: start.
// Iterator: about to yield 0
// Caller: 0
// Iterator: yielded 0
// Iterator: about to yield 2
// Caller: 2
// Iterator: yielded 2
// Iterator: about to yield 4
// Caller: 4
// Iterator: yielded 4
// Iterator: end.
^ This is an example of yield being used according to official docs.
what does "pauses execution and automatically resumes on the next frame" even mean?
Yield has two forms:
yield return-> produce next iteratoryield break-> signal the end of iteration
Pls use Debug.Log ples ples ples
I read the site
you pasting here the same things the site said isnt gonna change my misunderstanding
doesnt really matter what it is i guess, just use it and know what it does
The execution of a program stops when a coroutine is started, waits for the coroutine to finish, and then continues after the coroutine is complete.
thats the point, I dont know how to use it or what it does
Reading and adapting existing code will lead to a deeper understanding
@rose galleon using yield will suspend the coroutine. it continues once the amount of time or condition is complete. i said, "it returns," to insinuate that it leaves the coroutine, runs the next frame, checks the time/condition, and repeats until satisfied. when it returns and that time/condition is met, the coroutine will resume . . .
i showed you earlier how to use it
that mad complicated
just understand what the words yield and return mean and boom
yield is like the thingie that makes the coroutine wait for some time?
yield returns next iterator
coroutine does temporary program
womp womp the end
"wait for a return"
Yes
yield return new WaitForSeconds();
Theres also minutes and stuff
and so I use yield break if I just want to make it wait and then go back to the line that was going on before I called the IEnumerator?
huh? when a coroutine starts, execution resumes normally . . .
Oops yeah I said that wrong
In a coroutine, the program will stop for the duration that yield return takes, and then continue resuming normally
- Do something
- yield return new WaitForSeconds(2f); (wait)
- Do the rest
StartCoroutine kicks off that process of Do something / wait / do the rest
but if i want the rest to happen inside the void that I used to call the coroutine, i just use yield break?
I wouldn't worry about using yield break for your purposes
Give me an example problem at it will make more sense when written out
no, you have to do it in this one after the wait if you want it to be after the time has passed
i mean, if I only use one line of code in the coroutine, it doesnt really matter, does it?
yield break exits the wait loop
So it would indeed matter by signaling the exit of the iteration
The plug-and-play code is
IEnumerator MyCoroutine()
{
// Do stuff here
// Wait here
yield return new WaitForSeconds(5);
// Continue
// Do more stuff here
}
// Called by (in Unity):
StartCoroutine(MyCoroutine())
Using yield break here would just throw an error since it's only valid as a standalone statement.
it sounds confusing because you say, "the program." only the coroutine itself will stop. anything else running on a script will continue . . .
IEnumerator dashWait(float dashTime = 1f)
{
yield return new WaitForSeconds(dashTime);
isDashing = false;
}
like this?
yeah that works
perfect
les go
Just make sure you call it using StartCoroutine(dashWait(/* optional float param */)) in other code
yeye
me being picky: PascalCase that method, and is a default value necessary? will the dash time constantly change? if it's a single value that's assigned, you can just use that class variable in the method itself . . .
I think it could be useful in the future
like if the player got an upgrade that makes the dash longer?
You could store dashTime in a PlayerStats script and reference it from there. Might be a little more clean. It's more of a forward-looking concern
if your dash can be canceled, make sure to assign a coroutine variable when calling StartCoroutine. that way, you can cancel it by assigning it to null . . .
a lot of compiler errors popped up ;-;
show
things that were working before said that the private was invalid
nvm
is there like a history of changes in the code?
I kinda deleted an important thing but I dont wanna ctrl z my way through
Are you using git?
it's best to show us the error message and the script with the error in order to properly help . . .
ik whats the error, i just deleted the line of code that was working
re-write it. call it a learning experience. you'll only get better . . .
I found the timeline thing
nvm it does work
just because i made array 4 entries longer it broke my entire audio
interesting
i have awful loud deep fried audio but i can hear the base in it
https://hastebin.com/share/avalacumem.csharp
It was supposed to be working, but
1 - Its not checking for double clicks anymore, any click fills the click requirement
2 - the dash is very unstable
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
I tried changing my HandleRotation() function to update in LateUpdate on a whim... This has surprisingly smoothed it out a lot though I'm still not entirely sure why. Going to keep digging so I know the why to how I fixed my issue in case this is just a bandaid fix and I'm still doing something improperly.
https://paste.ofcode.org/ScWhFr8egFRsjgWq48jwyS : SC_PlayerMovement
https://paste.ofcode.org/Yvpk2Rdvgk3TisBimyJiaJ : SC_PlayerLook
https://paste.ofcode.org/jsrZRJLYzJJfiHz7dRZvcQ : SC_HeadBobController
here are my three scripts for my character. One is moving the player, one for camera controls, and the final one for view bobbing. everything works 100%, but I want to know how to make it so the view bobbing is only active while I am moving. can someone please help 🙏
Some testing ideas is try the rotation without attaching the cam to your player
and if you're not using cinemachine, it has some goodies to help with camera smoothing
I am using cinemachine actually. Thank you.
I'll try the rotation out without the cam. Though I'm going to take a break for now. Really fried my brain going through so many different ways to get where I am now.
The rotation script looks fine at first glance, so I expect it's just camera related
I don't quite understand I have just started using unity
What exactly is the question? If you're asking how to flip on and off the head bobble then that's just a flag to toggle.
Ideally you move the head back into a default position when toggling off
as easy as ifs and bools
no i want to have the head bobbing script only activate when I am moving
You've got your answers
but hoiw do i execute it
[Character movement script]
public bool characterMoving
//character movement script
if(walkspeed == 0)
{
characterMoving = false;
}
[Character bobbing script]
if(characterMoving == false)
{
//head bobbing script here
}
thank you
you would need to use instance = this too to reference the bool in another script
you know how to use that?
no
You definitely do not need to make a static accessor for this
Both scripts are gonna be on the same object, or at least bobbing on a child, so just do a serialized reference
Of course not...
oh right
and how would I do a serialized reference?
im no expert too, so maybe I should refrain from giving tips
public HeadBobScript headBob
Then drag and drop the headbob script into the field in the inspector
Serialized references are just drag and drop
and then where do I put it to turn it on and off for movement?
You could just enable and disable the headbob script entirely when you are moving or not
That will prevent update from running
[Character movement script]
public bool characterMoving
//character movement script
if(walkspeed == 0)
{
characterMoving = false;
}
[Character bobbing script]
if(PlayerMovement.characterMoving == false)
{
//head bobbing script here
or this
There are multiple syntax errors in this
sorry i am still a little confused
I mean, I guess it is just psuedocode.
Have you done !learn yet?
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
This is just an if statement essentially. So I do recommend taking the essentials and junior programmer pathways before continuing
anyways, just bumping this bcs it kinda got lost in this mess
Your timeSinceStartTime should be declared sooner, if not outside the method entirely
You also don't show where dash is called, so hard to say more than that
its in the update method
Also, not sure what "dash is very unstable" means
But to be fair, I did not watch the video
theres not much to affect there
I assumed, but you should of course show it...
not all double clicks activate it, its just messy really
Well, you don't show where it is activated. So I can't help with that
its literally just Dash();, I didnt think it was necessary
You only show 25 lines, starting at dash
The entire class is necessary
And nowhere in dash do you check for clicking, let alone DOUBLE click.
All that is in there is checking if a or d (or left arrow/right arrow) are pressed once
the starttime and timesincestarttime are measuring the distance of the clicks in time
You also don't show where canDash is set false, which is a HUGE thing that needs to be shown
They do not do that. Not as written at least
i mean, a week ago it was working
i dunno where I messed up
truuuue
Do you have any commits in version control from when it was working that you can check?
void Dash()
{
if(Input.GetButtonDown("Horizontal"))
{
if(IsGrounded())
{
canDash = true;
}
float timeSinceStartTime = Time.time - dashStartTime;
dashStartTime = Time.time;
if(timeSinceStartTime <= 0.2f && canDash == true)
{
Replaced part
//float dashStartTime = Time.time;
//float dashDuration = Time.time + 2f - dashStartTime;
//if(dashDuration <= 0)
//{
// isDashing = false;
//}
//isDashing = true;
//rb.velocity = new Vector2(rb.velocity.x * dashPower, rb.velocity.y);
//canDash = false;
//isDashing = false;
//Debug.Log("Dash");
}
}
}
this is the week earlier version
Did you type this out by hand?
How did it compile with:
float = Time.time
?
theres also a problem with that that Ill have to figure out later, because if you tap left and soon after right it dashes to the right, i should make it so its directional
this part was replaced in the new code, does it matter?
Well its a syntax error that would prevent the game from running
You have a type, with no variable name
I get that. I wanted to see how it was before, not how it exists now
the float was dashStartTime
which overlapped with the earlier instance of said code
so I erased it
it was just repeating an earlier line really, so it doesnt change anything
Ah ok, I was gonna say that not resetting dashStartTime may be an issue, so removing that may be part of the problem
Ah ok, I was gonna say that not resetting dashStartTime may be an issue, so removing that may be part of the problem
where do I reset it?
I would say INSIDE the if statement where you initiate the dash. Not before it
You should add some debug logs to show the actual values though
It will likely be quite illuminating
Debug.Log($"Start time: {dashStartTime}. Time since start: {timeSinceStartTime}");
I mean, you can just put a value in
Debug.Log(myVariable)
Or concatenation like this
Debug.Log("my value: " + myVariable)
I did string interpolation in my first example, because it is easy and clean. Better than concatenation for stuff like this
it was indeed
Start time should be reset on the first click, and time since start time on the second one
But start time is not being reset
Maybe refactor a little. Something like
void Dash()
{
if(Input.GetButtonDown("Horizontal"))
{
if(IsGrounded())
{
canDash = true;
}
if (firstDashPress)
{
dashStartTime = Time.time;
firstDashPress = false;
}
if((Time.time - dashStartTime) <= 0.2f && canDash == true)
{
firstDashPress = true;
isDashing = true;
rb.velocity = new Vector2(rb.velocity.x * dashPower, rb.velocity.y);
StartCoroutine(DashWait());
}
Debug.Log("Dash");
}
}
Done on my phone, so may have errors, and obviously untested
Behold my amazing programming skillz:
if (scrollsAllowed > scrollsAllowed)
{
scrollsAllowed = scrollsAllowed;
}```
hello i'm completely new to this thing, where should i start on my ar/vr journey
This is the coding channel, perhaps try #🥽┃virtual-reality #🤯┃augmented-reality or #💻┃unity-talk
Might want to brush up on !learn if you've never worked with Unity before.
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
don't really know where to ask this. I'm using Unity's new input system's split-screen implementation, as it's really convenient and easy to setup. It's amazing how fast it is to get something running. Only issue i'm having is the little control you get on the screens' positions, and most importantly relative size. As an example it would be impossible to achieve an effect like it takes two's camera system where if a player triggers an important event, his portion of the screen gets bigger to cover 70% or 80% of the screen. How could I do this without rebuilding the whole thing from the ground up? Editing unity's script wouldn't be too bad but any change would just get overridden. Ideas?
Probably #🖱️┃input-system is a good place for that question. Sounds super specific though, so no idea if you even get an answer there.
yeah, super dumb limitation tho imo
cause what the code is doing under the hood is just splitting the viewport by how many players there are idk why they couldn't make it more customizable
can u learn programming wrong or not?
like bad habits or anything
or something u do and that u cant improve anymore
I mean you can dig yourself holes if you're not sure how to properly plan your code and use inheritance
or becoming too reliant on static accessors
but there isnt rly a thing that can cause u to be plateaud or something? like skill in games, u have alot of bad habits for example in gaming itself, i wonder if its the same in programming and making games
i dont rly think so tbh, its all knowledge
you can fix all mistakes you learned beforehand
If you dont insist on keeping doing something like you lways did and actually learn new stuff/ adapt
yeah thats true, but what mistakes could u learn then in programming?
lmao
Not all needs commenting either
Ideally your code is writtn in a way where it explains itself easilly
There can be too many comments
Yes! Opening a sample project etc where each line of code has 4 lines of comments, buried in layers of inheritance and interfaces, just to uncover something that's a couple lines of code... drives me a bit crazy.
But a small blurb describing what your class was made for, and some comments here and there to explain why you are doing something, totally makes sense.
Anything I touch that involves with matrix, rotation, physics, I have to riddle with comments else ill come back the next day and be like wtf was I doing
not easy self-explanatory code
I also might leave a line or two in the code with links to reference documents. A good example of I'm doing some tricks with the khronos / VR interaction systems to find out what VR headsets are used (as OpenXR abstracts them away from us). So having a link there in the docs to show where those came from can be helpful.
So 9 months from now I'm not wondering why I used device.characteristics instead of OpenXR.name or something.
Ah, that's a good idea.
Yes, definitely. And the more you learn, the less mentors and harder to find access to others it can become. So you get a bit more isolated.
I should just link to the wikipedia page everytime I access some matrix4x4 column
Definitely!
would u guys say maths and programming is a talent? or just requires alot of practise?
I think a bit of both, it is like art. It is natural to some people, but anyone can still learn it, they just need dedication and time and patience and practice.
Both
It takes practice to write good readable code, and some people have the amazing talent to write truly horrific code
anyone know how I can make an ultrakill type movement for a PC game?
what's an ultrakill type movement?
let me send a youtube video of ultrakill and you can see the movement thing
its like face paced
Flesh Prison and Minos Prime Bossfight, P Rank in Normal Difficulty.
Surely the toughest boss fights in the game (probably before the rematch with Gabriel in ACT II). As always, not the most clean and efficent way to fight them, but an intense fight nontheless.
Thumbnail credit: u/chipwoahh (reddit)
ah like speedy doom like
eyah!
im trying to do something like that for my PC game
but ive kinda never coded in my life (well html but thats different)
I do have a port for doom 1 classic for VR on my itch page 😄
But the input is pretty easy for the most part
Some areas, like where he's running down a long rope thing,y ou probably will give them some "guidance" to keep them on a path these days.
are you able to give me some tips on how to make a movement similar? (if you know how sorta)
Sorry I sent some links from my pc, but it's not sending them for some reason lol
But this would be a pretty good straightforward input system to build out. The important part is the slow speed up, slow down where you probably don't stop completely instantly.
But yeah something akin to this would work
https://forum.unity.com/threads/doom-player-script.976419/
There we go
Hello everyone, I have a problem with my character, when I land from a jump, the player go into the ground and after tp himself on the ground to the right place... Can someone help me ?
thank you so much!
You need to post code.
im looking to create an animation to play in between levels as a transition, how would i accomplish this? would i create a new object with the animation or is there some other more regular method
animation timeline is a good starting point
unless we're talking about a screen fade / fade to black
which can just be lerping shader values over some texture over the camera
Please share the !code related to your movement
Bot isn't showing useful paste sites sadly
Hello,
I am currently trying to build a Pulley UI like, that will follow my mouse position and rotate towards it.
Basically I want to be able to turn it clockwise and anticlockwise, but currently I'm not quite understanding the why it work like this.
I want the player to turn the mouse clockwise for it to work
The UI in the hierarchy is like so :
UI > PulleyCanvas > Pulley > Handle
(The Pulley being the brown square and the handle the black rectangle)
If you have better solutions or a fix I would be glab to hear them !
https://pastebin.com/Qr6cxK73
!code
wouldnt it be z for world up on the angle axis
considering this is 2D
I'd also start debugging values to make sure the point values you are getting are correct
Ohhh yeah my bad, you're right I kept on the 3D part. Thanks !
Makes sense
im trying to use cinemachine virtuel camera for bounds but after i created the object the scripts i made for main camera doesnt work, from my understanding i cant add the scripts to main cam anymore and have to apply to my virtuel camere. but i cant seem to make the script work. im very new to coding so from my understanding its because the code is connected to main camera which is named Camera in the code. i tried looking it up and it seems to be named CinemachineVirtualCamera (also im like barely a week into coding so bear with my lack of understanding)
this is the working drag/move camera code, but after adding virtuel camera havent been able to make it work, i tried replacing all instances of camera with CinemachineVirtualCamera but that didnt seem to be right
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraMove : MonoBehaviour
{
private Vector3 Origin;
private Vector3 Difference;
private Vector3 ResetCamera;
private Vector3 velocity;
private bool drag = false;
private void Start()
{
ResetCamera = Camera.main.transform.position;
}
void Update()
{
Vector3 pos = transform.position;
pos.z = -10;
transform.position = pos;
if (Input.GetMouseButton(0))
{
Difference = (Camera.main.ScreenToWorldPoint(Input.mousePosition)) - Camera.main.transform.position;
if(drag == false)
{
drag = true;
Origin = Camera.main.ScreenToWorldPoint(Input.mousePosition);
}
}
else
{
drag = false;
}
if (drag)
{
Camera.main.transform.position = Origin - Difference * 0.5f;
Camera.main.transform.position = Origin - Difference;
}
if (Input.GetMouseButton(1))
Camera.main.transform.position = ResetCamera;
}
}
you need to get a reference to the CinemachineVirtualCamera, you cannot just replace the word Camera in your code with CinemachineVirtualCamera because that class does not have a main property that points to a specific instance like Camera does.
please also check the documentation pinned in #🎥┃cinemachine for guides and tutorials for how to use it
any reason my navmesh agbent stopping distance stops working entirely when its below 1?
Stopping distance of 1.1. ANd stopping distance of 1 hes just inside
is all "///" does is add comments in a darker colour
no, it also adds hint text when the commented class/method/variable is referenced
what is hint text
i did google but i dont get it
It's what you get when you hover over somthing in your IDE
then what didn't you get?
well when i searched "what is hint text c sharp" i just diddnt find anything relevant
Then I suggest you improve your google skills
i got dis
do you not know that in google you enter the keywords in order of importance to your search?
Try looking at other results. Not just the first one.
it's called reverse polish notation, but yes
good to know ty
Hey, I'm making and idle mobile game to experiment with it and created a scene for each "tab" in the game
but since I have logics that consists between scenes I made some classes with singleton, and was wondering if that's the best practice or is there a better way to manage those classes (for example the player class, and the idleManager class)
wdym by tab? should probably just be the same scene
Singleton AND DDOL ?
tab like "shop tab" "main tab" "guild tab" etc
can i have it all on the same scence even though i want to have completely different things displayed?
yes
i assume its just like a UI menu? yeah just toggle them off/on
depending on which one you click
then you are on the right track, just don't over do it or you'll end up in Singleton hell
not sure i understand, lest take Clash Royal for example, there are different tabs on the bottom and each display completely different scene
yeah no that would just be 1 scene
how?? it make no sence to me ):
why would you pack so many objects on the same scene?
the only different scene would be the actual scene where your playing the game and fighting
i come from fullstack background and it sounds bizzare to me haha
so you say that all the UI elements i see are just different panels that are being disaplyed on a canvas and all live on the same scene?
but how can you even see whats happening when you develop it? the scene window will have all of them on top of each other
you disable/enable what you need
because you disable them
only activate the one you are using
but also if you have a fullstack background, you might consider using UI Toolkit which is probably more like what you are used to
is this really the common practice for things like that?
yep, you could also use multiple canvases if you wish
oh, i didnt know what it was haha ill check it out
i wasted a day to figure out how to manage the scenes while changing tabs haha oh well better late than never
is there a common practice?
Depends on the exact usage. If the panels have no overlap I like to use multiple canvases, otherwise I use a panel structure within one canvas
so as long as its just simple point and click logic i should use panels and when i need actual animation and effects i should use new scene and gameobjects?
i guess they will all share the same bottom (tabs) and top (info bar)
generally, yes
but effects like gain coin on fireworks can live on panel too?
then a multi panel approach is probably best
wow interesting thanks!! glad i asked haha
if you think from a web dev perspective, where would you use divs and where would you use new pages?
i wanted to make it a SPA but didnt think panels could act as such because i only thought about the scenes
think, a panel is a div, a canvas/scene is a web page
I have a script that uses collision detections, for some reason only one collision is active at a time. Either I'm touching a wall, or I'm touching the ground, but never both at the same time. Not sure what to do.
https://gdl.space/ayonininut.cs
what to do when sample bytes are non dividable by 4?
according to your code you are hitting both or neither. And virtual, why?
I think I typed virtual a couple days ago planning to override it, but nothing is currently overriding it
in what context
loading them as audioclip
but you cannot override it, so thats a different problem
what your code does is
foreach (ContactPoint2D contact in collision2D.contacts)
{
Debug.Log(contact.normal);
if (contact.normal.y > 0.5f)
{
player.groundCheckCollision = true;
player.wallCheckCollision = true;
break;
}
else
player.groundCheckCollision = false;
player.wallCheckCollision = false;
}
which is damn silly
Ah, true
ye
so according to code, I should be able to check both together and separately right? but for some reason it's only checking one or the other
no, but both checks will happen, you need to limit your for loops to only run in the correct context
var bytes = System.Convert.FromBase64String(audiostring[0]);
float[] samples = new float[bytes.Length / 4];
Debug.Log(bytes.Length + " / " + samples.Length);
System.Buffer.BlockCopy(bytes, 0, samples, 0, samples.Length * 4);
var clip = AudioClip.Create("song", samples.Length, 2, 48000, false);
clip.SetData(samples, 0);
musicplayer.clip = clip;
musicplayer.Play();```
they were fine as pcm format but took insane amount to download
after turning to mp3 audio got crispy
you mean like 2 seperate scripts?
no, wrap the for loops in an if checking the collider hit
i'm curious why you have your audio clip encoded as a base64 string 🤔
this seems to do the same thing
it's only ever returning true on 1, but never both
because im downloading level as string and what is better way to get filestring than base64
if (collision.collider == // Ground collider
{
player.groundCheckCollision = false;
foreach (ContactPoint2D contact in collision2D.contacts)
{
Debug.Log(contact.normal);
if (contact.normal.y > 0.5f)
{
player.groundCheckCollision = true;
break;
}
}
}
}
if (collision.collider == // Wall check collider
{
player.wallCheckCollision = false;
foreach (ContactPoint2D contact in collision2D.contacts)
{
if (contact.normal.x > 0.5f)
{
player.wallCheckCollision = true;
break;
}
}
}
@queen adder
is the audio provided by other users or something? because if not, there's really no reason to even include the audio files directly in that string
yes
trying it right now
I had all my objects set to ground while testing cuz I figured it was an object I can touch, so I'm just renaming them to wall right now
best use tags or layers to differentiate between the two not names
anyway, the issue is likely how you are encoding it to base64 or how you split the string
string split gives exactly base64 string
store the audio separately. shoving multiple minutes of audio through base64 is ridiculous
you're inflating the data's size by 33%
better than pcm inflating data by 1500%
that is completely unrelated
base64 should be used when you need to turn binary data into something printable, so that you can store it in or send it through systems that need printable strings
nobody is going to copy-paste an entire base64'd song
string is necesary
whether you start with an mp3, an ogg, or a wav, base64 encoding increases its size
i can turn it to something else than base64 if you have better formats
why do you think it is necessary?
a better format is to do nothing
because its necesary to use only 1 link
why
unless you know i store level in audio format instead
you are not sending someone a URL that contains an entire 3-minute mp3 in it
oh, you mean storing the audio data in the linked level
just store all of this as binary data. there's no reason for the level to be base64'd at all
So I tried it the way you suggested ( i think ), but now it's not returning any collisions
if you must have one (and only one) file, you will need to concatenate the level data with the audio data
I'm so confused, sorry
you could serve a .zip archive containing all the files, perhaps
i used base64 just because im not 100% sure how proper binary data looks like
sometimes its 0 and 1s, sometimes its hex
literally just don't do the base64 encoding
that's it. you're done.
your checking LayerMasks not Layer id's
there are multiple valid ways to interpret binary data, yes...
honestly this is like a super XY Problem
explain the actual purpose of what you are attempting to achieve
not sure how to do this, I will look it up
XYZWɑ
Dont use LayerMask, use Layer
just storing and loading audio out of string
what is the actual purpose of doing that
please read the site boxfriend linked you to
well to play music in game from the any link player wishes to type in
and that link needs contain level objects and so on
this is a "custom level" system, isn't it
yes
again, you're talking about attempted solutions ("typing in links")
your goal is not to implement a way to type in links
your goal is to let people create custom levels with music
how are these custom levels constructed in the first place
they are made out of positions of many objects where to place what
i am not asking about the contents of your levels, i am asking how the custom levels are actually made.
do you have some sort of in-game level editor, are you expecting users to make the levels in unity, are they being made in some third party software
externally how
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To 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.
now, i am far from an expert, but i'm fairly certain osu does not store the audio data as a base64 string in its beatmaps
of course not
so then how are your custom levels actually being created
i setup server for downloading maps from mirror site, unzipping contents of it and mashing everything together into one string
because your xy questions always lead to different solution which im not able to execute
audio as string, everything stops here
because your solutions are generally stupid
i know we're a far cry from storing variable data in gameobjects names at this point, but come on at least try and do things the smart way. you're inflating your data by more than 30% so it's not like you're saving on storage costs by encoding the audio as a string. if you have the audio file already just store the path to it then use unity's handy audio clip download handler
no i can use raw bytes instead of base64 sure
just need learn on that rn
because im pretty sure i do can use blockcopy on string as well
alright good luck with that. none of this is legal btw because you absolutely do not have the rights to distribute these songs so good luck and try not to get sued
Question about singletons/DDOL, I see we use Destroy(this.gameObject); if the instance exists and i assume it's to prevent multiple instances, but when i ran the game without it i dont see extra "player" instances anywhere and if i do use it it breaks my panel because it's no longer have the text object in the player script
is the player actually DDOL though
yeah
did you setup the DDOL object correctly??
because if it is and you load whatever scene originally had it, then you absolutely would end up with multiple instances
how did you implement Destroy(gameObject)?
private void Awake()
{
if (instance != null && instance != this)
{
Destroy(gameObject);
return;
}
instance = this;
DontDestroyOnLoad(gameObject);
}
and if you are using the singleton pattern the entire point is to ensure that only one instance of the object ever exists at any given time. and destroying new instances is not what is causing issues with referencing other objects, it's the fact that when you change scenes those objects get destroyed so your DDOL object still references the destroyed ones
ohh so its because my panel is getting destroyed and created again so the player with the old panel reference loses it?
yes
yes, only the objects marked with DDOL persist between scenes. if that DDOL object has references, they will become null during scene change because those objects are destroyed . . .
thanks! well now im going to remove all of the tabs and have multiple panels on the menu scene
though i still need to have access to the player script from the game scene...
but with a singleton i complicate all the game objects that intercat with the player script
maybe i should have the player logic in a separate script like "idleManager" and it will be singleton. and all the other scripts from the other scenes will access it
As in the documentation (https://docs.unity3d.com/2021.3/Documentation/Manual/EditingValueProperties.html) I'm writing *=2 in the inspector field, but all the values are turned into zeros instead of being doubled. Am I missing something or is it bugged?
what was the value before?
was it 0,0,0?
aren't the values 0?
@languid spire sorry Steve I don't mean to trouble you right now, I just really can't figure this out. I redid my code to something more simple just to see if it is working. https://gdl.space/orawijequt.cs, but I'm still unable to have both booleans return true at the same time.
or if anyone else can help, the issue I'm having is my script won't touch the ground and wall at the same time
only separately for some reason
Oh, I've just read the note that proportion scaling doesn't work on multi-selection. I had multiple objects selected.
Wait, it still doesn't work for a single object...
It was 5.
oh thats fun another byte format
hello everyone. I just started game dev. So my character move fine but when i go diagonal it moves faster this is my code:
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
[SerializeField]
private Rigidbody2D rb; //Rigidbody = rb
[SerializeField]
private float speed;
private void Update()
{
//Controlls
rb.velocity = new Vector2(Input.GetAxis("Horizontal") * speed, Input.GetAxis("Vertical") * speed).normalized;
}
}
Why did they post a screenshot of using /=3 on mult-iselection when they pointed it doesn't work on multi-selection 🤔
.normalized didn't solve it . It make weird to move it's slow
Seriously, stop trying to store your audio files as strings. If you've already got the actual files then just download the files directly instead of encoding them as strings to download
you need to store the input in a vector, then normalize that, then set the velocity with the speed
multiply by speed after normalizing, not before
I did not understand sorry. Can u guys explain like i'm 6 y.o and have brain issues?
that is already the easiest explanation
try to understand it
alr thanks
currently, i cannot test, but it should work fine . . .
.normalize changes the length of the vector to 1. In your case the length of Vector would define how fast character moves. If you have speed like 1000 and Vector like (1000, 1000), then you normalize it, you will end up with Vector (0.7f, 0.7f). In other words: no matter what's inside of the Vector, you will end up with speed equal to 1, which is why you need to apply your speed modifier afterwards.
hey, I want to write a function so that if I click the LMB an Animator Trigger gets set. What function or command do I use to detect the click, regardless of the position of the mouse on screen? I have tried using the monoBehaviour.OnMouseDown but that only works in combination with a collider if I am not mistaken.
google -> unity how to detect mouse click
did it, only finding stuff on how to click on specific objects and not the general mouse click unfortunately
and i know how to implement that, my Point and Click game is almost finished lol
The answer is in the 2nd result of what I suggested to google
can you send me the link please?
thank you, that really didnt turn up for me
don't just search one thing and then give up searching... refine/ edit the search to get different results
that came up instantly with my search
i know, I just did that during a week long game jam but google sometimes is weird with what it shows
but again, thanks for the help
Normalizing a vector sets its length to 1.
You can then multiply that vector with a number to make it longer (so that you move faster)
rb.velocity = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical")).normalized * speed;
well thanks you all. I did this and it did solve diagonal fast movement but now i moves idk really weird i'm going to try solve it if i can't i'll probably come here again. thanks again
From my tests it looks like it works only if I keep the value on the left side (e.g. 5*2). *=2 just sets value to 0 the moment I type *.
show the code you are running
oh wait, this is in the inspector :p
...is it?
let me see what you're doing either way
This solution should work fine as long you're using digital inputs (e.g. keyboard). In case of analog values (e.g. gamepad sticks) it would be better to use version without .normalize (since max value should already be normalized).
i use keyboard. Yes it works but when i stop pressing button it moves a little bit like flying
hm, that's working fine for me when I multi-edit two cubes' positions
didn't we like explain it dozens of times what solution was lol
i tried the solutions but doesn't work
the time is working but it doesn't add seconds
what exactly "doesnt work"
it doesn't add time
Oh, I forgot about this edge case. You need to normalize Vector only if your inputs are not null.
var input = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"));
if (input.magnitude > 0) // if the legnth is longer than 0
rb.velocity = input.normalized * speed;
else
rb.velocity = Vector2.zero;
which script are you adding
Obstacle controller
are you calling Respawn
also, IMO you should almost never modify public variables directly
use a method, so you can stuff more stuff in there like an event
this way you are aware what happens after for sure
im calling respawn, the script that i made with score it worked propertly but this doesn't work
Then I assume something messes it up on my side. Perhaps some package (perhaps Odin?). Gonna test it on empty project later. Thanks for checking it out.
how do you know its called ? and how are you sure the value part was run? you don't have any debugging going on
i had debug i deleted it
im gonna try again
Thanks, it doesn't go more when i press for a sec but when i press for 3 or more sec it still go fly.
for example
timerScript.timer += 20f; // Update the TimerScript.timer with the new value
Debug.Log($"Timer added {timerScript.timer}");
it doesn't work if that doesn't work how does the score adds dfk
what exactly means "doesnt work"
you have to be specific
the debug log doesn't show
for u maybe it is mhm
unless timerScript were somehow null or another before it in that method, there is no possible way it wouldn't run unless you're not calling it
so what u suggest me doing to make the method running?
make sure the confidion is true ?
if (transform.position.y < -10f) // Assume obstacle falls below -10 units in Y position
....is this part even running at this point
the respawn is working
but the addtime is no
because if that wouldn't work it would respawn the obstacle but it respawns
and the score is being added
how do you know
you just said log isn't running
because there is text ui and it updates
i added the debug log to the wrong text
jesus
maria
so when you said this it was made up or what
no it's the problem
it doesn't add the specific seconds to the timer when the obstacle gets pushed by the player and the obstacle respawns it should add 20 seconds to the text ui
so you're saying this top line runs but bottom doesn't ?
// Add score when the obstacle respawns
Score.instance.AddScore(1);
// Add time to timer
timerScript.timer += 20f; // Update the TimerScript.timer with the new value```
so something is overwriting the timer's value?
prob this ^
also can you show the debug you added now
since you said you added to wrong thing before
timerScript.timer += 20f; // Update the TimerScript.timer with the new value
Debug.Log($"Timer added {timerScript.timer}");```
Ideally you should have a method, like AddScore.
Do you see how it is its own method
it shows this but it doesn't add
my bad
should've done this
Debug.Log($"Timer {timerScript.timer}");
timerScript.timer += 20f; // Update the TimerScript.timer with the new value
Debug.Log($"Timer added {timerScript.timer}");```
i have only 1 timerscript and other must be in obstacle controller
how do you assign timerScript in Obstacle controller
and this is on the same object as ObstacleController ?
can you show the ObstacleController's object inspector
please dont crop, show entire object
is this object LevelManager ?
no
ok I see whats wrong then
yes
great,now look
timerScript = GetComponent<TimerScript>();```
what do you. think this line of code is doing
in ObstacleController
getting reference
from where
to timerscript component my is attached to same object
mhm
hey Remember this
yes i do remember
ok so you know what the fix is now right ?
;Dd
i change all the code
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovemet : MonoBehaviour
{
[SerializeField]
private float moveSpeed;
private void Update()
{
//Movement
float moveX = 0f;
float moveY = 0f;
if (Input.GetKey(KeyCode.W)) moveY = +1f;
if (Input.GetKey(KeyCode.S)) moveY = -1f;
if (Input.GetKey(KeyCode.A)) moveX = -1f;
if (Input.GetKey(KeyCode.D)) moveX = +1f;
Vector3 moveDir = new Vector3(moveX, moveY).normalized;
transform.position += moveDir * moveSpeed * Time.deltaTime;
}
}```
and now it's work
if you want collisions ever at some point you should not be moving transforms direcly
esp for character
rb.moveposition
what it does is checks if your object is hitting anything along the way when moving a position
what should i do than
use either a rigidody's movement or Character Controller
still no clue how to fix that script
they both have methods which respects collider
movePosition is same as teleportation so no
it will phase through walls
its meant for kinematics
wtf mate
You're grabbing the wrong component..

now i get it
if you assign components in inspector you should not use GetComponent
After 20 hours
as soon as game ran, it runs Start and it will run GetComponent
🎊
lucky for you it did have it on the same gameobject so it didn't throw a null reference
Have you figured out that stuff with singletons tho?
wdym?
i didn't add singletons
You seem like you know what you are doing can you help me?
So i did change my code back to this:
{
[SerializeField]
private float moveSpeed;
[SerializeField]
private Rigidbody2D rb;
private void Update()
{
rb.velocity = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical")).normalized * moveSpeed;
}
}```
but for some reason when i go any direction more than 1 second my character floating and i have no idea what to do
i believe that was the other person . . .
It wasn't
in an open world game is it efficient to detect which mesh colliders are within range and disable them? or does the physics engine already do that?
if u talking about the Playerwalksound they now work propertly after Gameoverui they disable
Well, you should be using Singletons for that
can you show what you mean "floating"
I can't tell exactly type of game you're going for
Also use FixedUpdate
thats prety much what camera culling does
2d top down. Character still moves when i no longer press button for some time like 1 or 2 sec
And GetAxisRaw to not normalize
so when you let go of the keyboard keys it keeps going?
yes
for a moment
🎊
well that's an entirely different channel. i was speaking of in here . . .
also you should deff use FixedUpdate to move, keep the inputs in Update
Thank you all it did solved when GetAxisRaw and FixedUpdate
I simply wondered whether they have solved the issue from earlier, as they have mentioned needing 20 hours for something
How though.
It doesn't make sense to be, the issue shouldn't be solved simply from that little change
the smoothing was prob messing with their let go (probably feels laggy with smoothing)
GetAxis is smoothed and will ease to 0. GetAxisRaw has no smoothing applied, thus will use the absolute value . . .
I have no idea
It is explained in the message above
Oh
I forgot about the GetAxis' smooth
Hey i have another question can u suggest me how do i make that in diffrent scene it would add diffrent time? Like in Level 1 it would add 20 in Level 2 it would add 10 In Level 3 It would add 5?
Make a lambda switch for the current scene
could also use some kinda of multiplier already saved in each level
score += SceneManager.GetActiveScene().name switch
{
"Level 1" => 20,
"Level 2" => 10,
"Level 3" => 5,
_ => 0
}
Of course, gotta have the tuples for all of them
thanks
Looking fine to me.
I believe in you!
Also, doesn't this have any formula?
||```cs
score += 20 * (1 / Regex.Match(SceneManager.GetActiveScene().name, @"\d+"));
Whatever. There is no formula
I want to spawn capsules when I press D, and have a 2 second cooldown before you can spawn another capsule. Duplicating using instantiate. This is the one ive written, but it summons a lot of capsules https://gdl.space/xodojafaba.cpp
how do I make it stop instantiating
for 2 seconds
why not do everything inside coroutine
everything like the keycode stuff as well?
does wait for seconds not work here
Or just do it all in Update
i am
alrigh
use update with a timer
nothing in this code even makes sense
the bool does nothing
time.time then
i forgor to delete that, my bad chat
if you need the coroutine one
IEnumerator Start()
{
while(true)
{
yield return new WaitUntil(() => Input.GetKeyDown(KeyCode.D));
//Instantiate
yield return new WaitForSeconds(2);
}
}
````I think might work
lambda function in this case
what does that mean
just like...
float cooldown = 0;
void Update() {
if (cooldown <= 0 && Input.GetKeyDown(KeyCode.D)) {
Instantiate(prefab);
cooldown = 2;
}
cooldown -= Time.deltaTime;
}```
@plush oxide
And I don't understand this spawn = true why is it a bool
it should just a function that actually spawns the thing
i see
okay ill read that
thats kinda smart
yeah ill try that
this ill have to read a bit to understand
but I think I got the general idea of how to fix this
yeah coroutines aren't simple (at first) but eventually powerful to learn for other stuff
is there any way 2 get state of mouse (clicked, not clicked), that works if clicked in any screen dot, from any pos, in any dir?
if (Input.GetMouseButtonDown(0)) { }
if you're talking about receiving input outside of your game window...
you're getting into platform-specific code
but maybe I'm just misunderstanding your question
it seems like always false
then the code isnt running
is the script on an activate game object and is this code in Update?
i want 2 make dragging "paint" by gameobjects
Input.GetMouseButtonDown is true for only one frame
use Input.GetMouseButton if you want to know if it's up or down, full stop
active, but in OnMouseEnter
then that would be almost impossible for it to run
OnMouseEnter relies on colliders
yes
Why would you use that if you want to be called from anywhere
idk, i just wanted that all understanded that i don't need OnMouseDown or something like that
we know, as Fen suggested you should use GetMouseButton but inside Update (Inputs are typically "polled" here)
thx
it works in OnMouseEnter also
OnMouseEnter should not be inside Update no , it would never work
OnMouseEnter is a special Unity message from MB script, its called when mouse goes over a collider
How do I change the scale of game objects in my world space to the same scale as canvas ui?
whats the usecase ?
guy, it works. just works
The proper use of OnMouseEnter is this:
https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnMouseEnter.html
I'm building an android app where the ui scales with the screen. The game objects (enemies, player) are within the screen boundaries. However, on a smaller mobile resolution, these game objects become large and are cut out by the edges of screen. Similarly, on large resolutions, these game objects becomes very small.
oh, you mean you used Input.GetMouseButton inside of the OnMouseEnter method
that sounds reasonable enough
the timing would have to be insane
public class OnChessUI : MonoBehaviour
{
public EventHandler mouseEnter;
public void OnMouseEnter()
{
if(mouseEnter != null)
mouseEnter(1, EventArgs.Empty);
}
}```
```c#
cell.GetComponent<OnChessUI>().mouseEnter = (e, s) =>
{
if (ActiveUI.builder && Input.GetMouseButton(0))
{
/*my actions*/
}
};```
so you want your sprite objects to scale with Screen ?
not sure what UI has to do with anything
Sounds like you need to adjust the camera size
Yes that's right
changing your resolution should not change how large objects appear to be
the camera is going to render exactly the same (whether it's perspective or orthographic)
unless these are actually images on a canvas
Ah I see, thanks. I think the main problem is because of how objects are not scaling, they are rendering outside of screen space if I shrink the screen in free aspect
are these objects images on a canvas?
No, they are outside of canvas, in the root directory with main camera
I made this infographic
ah, you're talking about changing the aspect ratio
Is this a perspective camera or an orthographic camera?
Orthographic, it is in 2d
Cinemachine could do this for you. It can adjust a camera's ortho size to keep an object (or several objects) in frame
alternatively, you can adjust the ortho size to make sure the camera covers at least a certain amount of space
to fit a square, you'd do something like this:
float minSize = 10;
float screenRatio = Screen.width / Screen.height;
float ySize = minSize; // ortho size is vertical, so just set this to 10, always
float xSize = minSize / screenRatio; // for a narrow screen, we need to make the camera zoom out
Camera.main.orthographicSize = minSize / 2; // the orthographic size is half of the screen's height
Ok thanks, I will look into it🙂
To fit a non-square, you'd need to add an extra factor in when calculating xSize
e.g. double it to fit a 2:1 rectangle on your screen
https://gdl.space/bimavofate.cs this is for duplicating capsules using instantiate and having a 2 second cooldown before you can again. It doesnt wait for 2 seconds though and when I press D, it doesnt spawn 1 and spawns more
cooldown starts at 0
so it will instantly spawn something
nothing in your code checks for keyboard input, so I would not expect pressing D to do anything
oh
Input.GetKeyDown
i had a moment
I see
💥
This looks fine, then. It will spawn one object and set cooldown to 2
pressing D within 2 seconds should do nothing
I would have the IF for the cooldown simply return after decrementing, since there's no need to check for input if the cooldown is still in effect
it doesnt spawn 1 and spawns more
do you mean that hitting D spawns many objects instantly?
no, that happened earlier, now It duplicates whatever is on scene
i shouldve specified
my bad chat
i don't know what "whatever is on scene" means
whatever capsules are on scene
Is your script on the object that you're instantiating?
it duplicates them
that does sound plausible
yeah
is that the problem
tada!
Well yes, because now all the new ones are also listening for D and then making more
Yeah, put it on something that's sitting in the scene and handles that one task
alright , ill try that and message here again
Its pretty common for a scene to have a bunch of game objects that just run logic and have no mesh or sprite
most of my game objects have no physical presence
I have a script that's getting too long. I'm trying to break it up for cleanliness/organizational purposes, but if I move an instance of someObject from script A to script B, it would be nice if script A could reference the instance of someObject without needing to prepend it with scriptB. How can I make all public members of a script global? Or, how can I give script A access to everything in script B without having to prepend "scriptB"?
you cannot.
you're referencing a specific instance of a component
how would you know which ScriptB you're talking about if you didn't have to actually use a reference to a ScriptB?
It might be that what they need is a singleton, or static class, if they want global access to something
But edepends on usecase
quick question, if i wanted to make a object that followed the camera in a set location, that i still could have scripts on and still interact with(trigger collider), i should use viewport space right? im trying to figure out how to make things like a pause button, a text box with text and hint button that stays in assigned screen locations.
those should just use a Canvas
a canvas in either of the "Screen Space" modes will work
ah! okay!
Screen Space - Overlay draws directly onto the screen, and Screen Space - Camera follows the camera around
Yeah, single instance of both A and B. Singleton or static is fine, but curious if there's some easy way to "include" all of B in A, as if it were part of the script
There are partial classes
if you literally just want to break a single class's definition up into several parts
thank you so much
public partial class Foo {
public int one;
}
public partial class Foo {
public int two;
}
huh
I tried doing this once. It wasn't a great experience: I had trouble finding anything, since I had way too much functionality jammed into one class in the first place
Does that work, with Monobehaviours?
I refactored my game to get the code out of the giant class entirely
I don't know about that.
oh wait, yes it does lol
because I did it
I also avoid partial classes. I'd rather refactor the massive class into smaller utility ones that the main one can use
partial classes are great for codegen, where you want to be able to generate a class in several independent steps
but not for fixing a class that's just Too Big
partial is also sometimes used when multiple coders are involved, but that's better served with source control apps
Yeah, I just know I'd lose half a day refactoring it the "right way", and since I'm nearly done with this part, I can't decide if it's worth the effort
but thanks for the pointers anyhow.
If you use a few fields or properties from another object very regularly, you could do something like this: