#💻┃code-beginner

1 messages · Page 355 of 1

knotty ferry
#

it doesn't even work at start ;DD

rich adder
#

ok so Invoke is not running ?

ionic plank
#

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 ?

knotty ferry
#

but the seconds doesn't add

#

when obstacle respawns

rocky canyon
rich adder
rocky canyon
#

are you adding it to the variable that ur printing out?

ionic plank
rocky canyon
#

you can edit prefabs

rich adder
rocky canyon
#

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

rotund forum
#

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.

ionic plank
#

!code

eternal falconBOT
ionic plank
eternal needle
hasty sleet
#

This is an interesting way to describe it. Kind of insightful with the concise phrasing

rocky canyon
#

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

languid spire
knotty ferry
#

maybe it would work

rocky canyon
#

it doesn't matter what u name it

knotty ferry
rocky canyon
#

b/c ur giving it the Text gameobject's reference

rocky canyon
knotty ferry
rocky canyon
#

the script i copied didn't even have a method to add time to it..

knotty ferry
umbral rock
#

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?

wind raptor
#

How do I change these values in code? (figured it out. offsetmin/max)

wind raptor
#

You don't know what you don't know, and much of that gets picked up as you go

#

Yo

knotty ferry
ionic plank
ionic plank
wintry quarry
#

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);

ionic plank
#

what should i put instead ?

umbral rock
#

what does this mean

slender nymph
#

it means exactly what it says. you do not have an input button called "jump" set up in the input manager settings

wintry quarry
#

By default there's one called "Jump", maybe you meant to use that?

umbral rock
#

what do u mean

wintry quarry
umbral rock
#

oh, i need to use capital inn the beginning

#

ait, i'll try, thank u

late burrow
#

system.buffer.blockcopy is able to create any variable from just bytes?

polar shoal
#

did i already say hi here because i don't see it anymore

#

oh no I did not

calm dove
#

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 ?

polar shoal
#

!vs

eternal falconBOT
#
Visual Studio guide

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)

polar shoal
short hazel
late burrow
#

aw

#

maybe there something else that can create non primitives out of bytes

#

i searched for such thing for years

short hazel
#

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

late burrow
#

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

rocky canyon
#

go home compression algorithm, you're drunk 🍺

late burrow
#

any kind of compressing resulted in white noise from audio clip

rocky canyon
#

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);

eternal needle
rocky canyon
polar shoal
#

how could I make wall jumping for my 3d game?

polar acorn
#

Which is the type you want to add a function to

eternal needle
rocky canyon
#

whats the proper way to implement extension methods..

#

would i put it in a static class?

eternal needle
rocky canyon
#

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

eternal needle
#

oh sorry i confused myself, yea it has to be in a static class too

rocky canyon
#

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

rocky canyon
#

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)
late burrow
#

do audio samples have to be in pcm or can be some more sane format?

tranquil hollow
#

how can i set a definition for left?

polar acorn
#

Oh, actually, Vector3 does have left

#

It doesn't have Left though

tranquil hollow
#

i didint get it*

#

sry

polar acorn
tranquil hollow
polar acorn
#

there is no Left. There is a left though

tranquil hollow
#

oh

#

ty

rotund forum
#

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)

dusty shell
#

!code

eternal falconBOT
dusty shell
tough trench
#

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?

summer stump
#

That will make an infinite loop

tough trench
#

Sorry about that

#

its a equal sign

summer stump
#

Ah ok
Remove the i = part
But that should not be the issue

#

Any other code?

tough trench
#

Thank you that fixed it

summer stump
#

Ah ok. Glad it worked

rich adder
dusty shell
#

OnCollision or onTrigger?

rich adder
dusty shell
#

Just as a trigger

rich adder
#

so use OnTrigger

dusty shell
#

Yeah so I used the collider.tag and it returned untagged

#

Even tho the play is colliding with the collider

rocky canyon
#

is the collider have a tag?

rich adder
dusty shell
#

I just realized tag and game object name are two different things

rocky canyon
#

yes.

rich adder
#

and you for sure dont want to use names

dusty shell
#

I always thought they were the same

rocky canyon
#

tags are a finite source

dusty shell
rocky canyon
#

may need them for sum'n else

#

if u do use tags use CompareTag("YourTag");

#

and not if .tag ==

rich adder
#

no intellisense for strings

#

and gameobject names change, or if they do everything breaks.

dusty shell
#

I didn’t know you’re meant to tag game objects

rich adder
#

yeah tags are ok. I just personally would rather use a component

#

since unity is component based its perfect

dusty shell
#

Wdym?

rich adder
#

thats component

#

but ideally you would try to find one like a tag not compare

dusty shell
rich adder
#

No i just meant components in general

#

Transform, Collider etc..

#

they're all components

rocky canyon
#

i like cs private void OnTriggerEnter(Collider other) { if(other.TryGetComponent(out EnemyHealth enemyHealth)) { enemyHealth.health -= damageAmount; } } trygets

dusty shell
#

I mean the someOtherCollider for me would be the player collider?

rocky canyon
#

lol.. my tag system

   if(other.TryGetComponent(out BlueScript blue))
        {
            //Make Blue Do();
        }```
rich adder
#

it was just a random example

#

from your script

rocky canyon
#

u could compare ur players collider if u wanted to

dusty shell
#

Yeah I get what y’all saying

#

Thank y’all so much ts finally making sense

dusty shell
#

It says rb velocity is 0, 0 but it's moving

hasty sleet
dusty shell
#

Thought it would work that out for me cl😞

#

How’d I change that then

hasty sleet
#

What problem are you trying to solve?

#

rb.velocity is indeed zero, and your character is moving properly. Are you trying to measure something?

dusty shell
#

I wanna use the platform velocity to move the character

#

When they’re in a platform I mean

hasty sleet
#

When they're in a platform?

dusty shell
#

Is there another way I can do this?

rose galleon
#

hey

dusty shell
#

That code snippet is for moving platforms

hasty sleet
#

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

rose galleon
#

I was working on a sort of timer for my dash, and I forgor how to use time

hasty sleet
#

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

dusty shell
rose galleon
dusty shell
hasty sleet
#

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

dusty shell
hasty sleet
#

First, try Rb.MovePosition(transform.position + direction * speed * Time.deltaTime)

deft grail
hasty sleet
#

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.

dusty shell
#

Thanks so much tho

hasty sleet
#

No problem! I recommend reading Rigidbody documentation on Unity and scanning for built-in methods that might seem useful to you

dusty shell
#

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

rose galleon
deft grail
rotund forum
# rotund forum I believe I have tried everyone's suggestions for how to fix this. I have commen...

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.

https://gdl.space/atemujagic.cpp

rose galleon
#

what does yield do?

cosmic dagger
#

it waits based on the amount of time you provide or the condition . . .

hasty sleet
#

Yield provides the next value in an iteration

cosmic dagger
#

then it returns to that same spot after the time expires . . .

hasty sleet
hasty sleet
rose galleon
#

i dunno

hasty sleet
#

Read the official documentation

rose galleon
#

it made sense for me

hasty sleet
#

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.

rose galleon
#

what does "pauses execution and automatically resumes on the next frame" even mean?

hasty sleet
#

Yield has two forms:

  • yield return -> produce next iterator
  • yield break -> signal the end of iteration
random cave
rose galleon
#

you pasting here the same things the site said isnt gonna change my misunderstanding

deft grail
hasty sleet
rose galleon
hasty sleet
#

Reading and adapting existing code will lead to a deeper understanding

cosmic dagger
# hasty sleet What do you mean?

@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 . . .

deft grail
random cave
#

just understand what the words yield and return mean and boom

rose galleon
#

yield is like the thingie that makes the coroutine wait for some time?

hasty sleet
#

yield returns next iterator
coroutine does temporary program
womp womp the end

random cave
#

"wait for a return"

random cave
#

yield return new WaitForSeconds();

#

Theres also minutes and stuff

rose galleon
#

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?

cosmic dagger
hasty sleet
#

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

rose galleon
hasty sleet
#

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

deft grail
rose galleon
hasty sleet
#

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.

cosmic dagger
rose galleon
#
    IEnumerator dashWait(float dashTime = 1f)
    {
        yield return new WaitForSeconds(dashTime);
        isDashing = false;

    }
#

like this?

hasty sleet
#

perfect

rose galleon
#

les go

hasty sleet
#

Just make sure you call it using StartCoroutine(dashWait(/* optional float param */)) in other code

rose galleon
#

yeye

cosmic dagger
rose galleon
#

like if the player got an upgrade that makes the dash longer?

hasty sleet
#

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

cosmic dagger
#

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 . . .

rose galleon
hasty sleet
#

show

rose galleon
#

things that were working before said that the private was invalid

rose galleon
#

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

hasty sleet
#

Are you using git?

cosmic dagger
#

it's best to show us the error message and the script with the error in order to properly help . . .

rose galleon
cosmic dagger
#

re-write it. call it a learning experience. you'll only get better . . .

rose galleon
late burrow
#

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

rose galleon
rotund forum
craggy ingot
timber tide
#

and if you're not using cinemachine, it has some goodies to help with camera smoothing

rotund forum
timber tide
#

The rotation script looks fine at first glance, so I expect it's just camera related

polar shoal
timber tide
#

Ideally you move the head back into a default position when toggling off

craggy ingot
#

no i want to have the head bobbing script only activate when I am moving

timber tide
#

You've got your answers

craggy ingot
#

but hoiw do i execute it

rose galleon
#

[Character movement script]
public bool characterMoving

//character movement script
if(walkspeed == 0)
{
characterMoving = false;
}

[Character bobbing script]
if(characterMoving == false)
{
//head bobbing script here
}

craggy ingot
#

thank you

rose galleon
#

you would need to use instance = this too to reference the bool in another script

#

you know how to use that?

craggy ingot
#

no

summer stump
#

You definitely do not need to make a static accessor for this

summer stump
#

Both scripts are gonna be on the same object, or at least bobbing on a child, so just do a serialized reference

summer stump
craggy ingot
#

and how would I do a serialized reference?

rose galleon
#

im no expert too, so maybe I should refrain from giving tips

summer stump
#

Serialized references are just drag and drop

craggy ingot
#

and then where do I put it to turn it on and off for movement?

summer stump
rose galleon
#

[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

summer stump
#

There are multiple syntax errors in this

craggy ingot
#

sorry i am still a little confused

summer stump
#

I mean, I guess it is just psuedocode.

summer stump
eternal falconBOT
#

:teacher: Unity Learn ↗

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

summer stump
#

This is just an if statement essentially. So I do recommend taking the essentials and junior programmer pathways before continuing

rose galleon
summer stump
#

You also don't show where dash is called, so hard to say more than that

rose galleon
summer stump
#

Also, not sure what "dash is very unstable" means
But to be fair, I did not watch the video

rose galleon
#

theres not much to affect there

summer stump
rose galleon
summer stump
rose galleon
summer stump
#

You only show 25 lines, starting at dash

summer stump
#

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

rose galleon
#

the starttime and timesincestarttime are measuring the distance of the clicks in time

summer stump
#

You also don't show where canDash is set false, which is a HUGE thing that needs to be shown

summer stump
rose galleon
#

i dunno where I messed up

summer stump
rose galleon
#
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

summer stump
#

Did you type this out by hand?
How did it compile with:
float = Time.time
?

rose galleon
rose galleon
summer stump
#

You have a type, with no variable name

rose galleon
#

that no longer exists

#

I just didnt have creativity for a name at that time

summer stump
rose galleon
#

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

summer stump
#

Ah ok, I was gonna say that not resetting dashStartTime may be an issue, so removing that may be part of the problem

rose galleon
#

where do I reset it?

summer stump
#

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

rose galleon
#

it would

#

tho I only know how to make debug logs write out strings

#

not values

summer stump
#

Debug.Log($"Start time: {dashStartTime}. Time since start: {timeSinceStartTime}");

summer stump
#

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

rose galleon
#

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

summer stump
#

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

topaz mortar
#

Behold my amazing programming skillz:

if (scrollsAllowed > scrollsAllowed)
{
    scrollsAllowed = scrollsAllowed;
}```
winter bison
#

hello i'm completely new to this thing, where should i start on my ar/vr journey

ivory bobcat
eternal falconBOT
#

:teacher: Unity Learn ↗

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

bright violet
#

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?

fossil drum
bright violet
#

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

umbral rock
#

can u learn programming wrong or not?

#

like bad habits or anything

#

or something u do and that u cant improve anymore

timber tide
#

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

umbral rock
#

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

green ether
#

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

umbral rock
#

yeah thats true, but what mistakes could u learn then in programming?

timber tide
#

worst mistakes is to not comment on your code

#

which is something I'm bad at ;)

umbral rock
#

lmao

green ether
#

Not all needs commenting either

#

Ideally your code is writtn in a way where it explains itself easilly

#

There can be too many comments

tough lagoon
#

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.

timber tide
#

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

tough lagoon
#

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.

timber tide
#

Ah, that's a good idea.

tough lagoon
timber tide
#

I should just link to the wikipedia page everytime I access some matrix4x4 column

tough lagoon
#

Definitely!

umbral rock
#

would u guys say maths and programming is a talent? or just requires alot of practise?

tough lagoon
#

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.

burnt vapor
#

Both

#

It takes practice to write good readable code, and some people have the amazing talent to write truly horrific code

low sandal
#

anyone know how I can make an ultrakill type movement for a PC game?

tough lagoon
#

what's an ultrakill type movement?

low sandal
#

its like face paced

tough lagoon
#

ah like speedy doom like

low sandal
#

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)

tough lagoon
#

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.

low sandal
#

are you able to give me some tips on how to make a movement similar? (if you know how sorta)

tough lagoon
#

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.

#

There we go

ionic plank
#

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 ?

cosmic mural
#

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

timber tide
#

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

burnt vapor
#

Bot isn't showing useful paste sites sadly

cosmic flicker
#

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

ionic plank
#

!code

timber tide
#

considering this is 2D

#

I'd also start debugging values to make sure the point values you are getting are correct

cosmic flicker
raven ferry
#

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;

    }
}
slender nymph
#

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

raven ferry
#

okay! great thank you!

#

i really appreciate the help

lavish magnet
#

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

molten dock
#

is all "///" does is add comments in a darker colour

languid spire
molten dock
#

i did google but i dont get it

languid spire
#

It's what you get when you hover over somthing in your IDE

languid spire
molten dock
#

lol

#

yeah i do know what a hint is

languid spire
#

then what didn't you get?

molten dock
#

well when i searched "what is hint text c sharp" i just diddnt find anything relevant

languid spire
molten dock
#

i got dis

languid spire
teal viper
#

Try looking at other results. Not just the first one.

molten dock
#

nope

#

should i do my google searches caveman style

languid spire
#

it's called reverse polish notation, but yes

molten dock
#

good to know ty

willow breach
#

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)

deft grail
willow breach
willow breach
deft grail
#

depending on which one you click

languid spire
# willow breach yes

then you are on the right track, just don't over do it or you'll end up in Singleton hell

willow breach
deft grail
willow breach
deft grail
#

the only different scene would be the actual scene where your playing the game and fighting

willow breach
#

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

slender nymph
#

you disable/enable what you need

deft grail
#

only activate the one you are using

slender nymph
#

but also if you have a fullstack background, you might consider using UI Toolkit which is probably more like what you are used to

willow breach
#

is this really the common practice for things like that?

languid spire
willow breach
willow breach
willow breach
languid spire
#

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

willow breach
#

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?

willow breach
willow breach
#

but effects like gain coin on fireworks can live on panel too?

languid spire
willow breach
valid roost
#

Just updated my unity editor and now i get this warning

#

how do i fix

languid spire
#

if you think from a web dev perspective, where would you use divs and where would you use new pages?

willow breach
#

i wanted to make it a SPA but didnt think panels could act as such because i only thought about the scenes

languid spire
#

think, a panel is a div, a canvas/scene is a web page

queen adder
#

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

late burrow
#

what to do when sample bytes are non dividable by 4?

languid spire
queen adder
slender nymph
late burrow
#

loading them as audioclip

languid spire
#

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

queen adder
#

one is checking the contact.normal.x

#

they don't both check y

languid spire
#

Ah, true

queen adder
#

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

languid spire
late burrow
#
        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
queen adder
languid spire
slender nymph
queen adder
#

it's only ever returning true on 1, but never both

late burrow
languid spire
#
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

slender nymph
late burrow
#

yes

queen adder
#

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

languid spire
slender nymph
# late burrow yes

anyway, the issue is likely how you are encoding it to base64 or how you split the string

late burrow
#

string split gives exactly base64 string

swift crag
#

store the audio separately. shoving multiple minutes of audio through base64 is ridiculous

#

you're inflating the data's size by 33%

late burrow
#

better than pcm inflating data by 1500%

swift crag
#

that is completely unrelated

swift crag
#

nobody is going to copy-paste an entire base64'd song

late burrow
#

string is necesary

swift crag
late burrow
#

i can turn it to something else than base64 if you have better formats

slender nymph
swift crag
late burrow
#

because its necesary to use only 1 link

slender nymph
#

why

late burrow
#

unless you know i store level in audio format instead

swift crag
#

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

queen adder
swift crag
#

if you must have one (and only one) file, you will need to concatenate the level data with the audio data

queen adder
#

I'm so confused, sorry

swift crag
#

you could serve a .zip archive containing all the files, perhaps

late burrow
#

i used base64 just because im not 100% sure how proper binary data looks like

#

sometimes its 0 and 1s, sometimes its hex

swift crag
#

that's it. you're done.

languid spire
swift crag
slender nymph
queen adder
languid spire
late burrow
#

just storing and loading audio out of string

swift crag
#

No.

#

That is your attempted solution.

slender nymph
swift crag
#

please read the site boxfriend linked you to

late burrow
#

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

swift crag
#

this is a "custom level" system, isn't it

late burrow
#

yes

swift crag
#

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

slender nymph
#

how are these custom levels constructed in the first place

late burrow
#

they are made out of positions of many objects where to place what

slender nymph
#

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

late burrow
#

no it would burn my game they are made externally

#

i just have loader for them

slender nymph
#

externally how

late burrow
#

fine

#

they are osu maps

barren scroll
#

!code

eternal falconBOT
slender nymph
late burrow
#

of course not

slender nymph
#

so then how are your custom levels actually being created

late burrow
#

i setup server for downloading maps from mirror site, unzipping contents of it and mashing everything together into one string

slender nymph
#

why

#

just store the path to the audio file and download the audio file directly

late burrow
#

because your xy questions always lead to different solution which im not able to execute

#

audio as string, everything stops here

slender nymph
#

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

late burrow
#

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

slender nymph
#

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

willow breach
#

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

slender nymph
#

is the player actually DDOL though

willow breach
#

yeah

cosmic dagger
slender nymph
#

because if it is and you load whatever scene originally had it, then you absolutely would end up with multiple instances

cosmic dagger
#

how did you implement Destroy(gameObject)?

willow breach
#
private void Awake()
    {
        if (instance != null && instance != this)
        {
            Destroy(gameObject);
            return;
        }

        instance = this;
        DontDestroyOnLoad(gameObject);

    }
slender nymph
#

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

willow breach
#

ohh so its because my panel is getting destroyed and created again so the player with the old panel reference loses it?

slender nymph
#

yes

cosmic dagger
#

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 . . .

willow breach
#

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

solemn bobcat
deft grail
#

was it 0,0,0?

cosmic dagger
#

aren't the values 0?

queen adder
#

@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

solemn bobcat
#

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...

solemn bobcat
late burrow
#

oh thats fun another byte format

velvet sierra
#

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;

    }
}
solemn bobcat
#

Why did they post a screenshot of using /=3 on mult-iselection when they pointed it doesn't work on multi-selection 🤔

velvet sierra
slender nymph
deft grail
solemn bobcat
velvet sierra
#

I did not understand sorry. Can u guys explain like i'm 6 y.o and have brain issues?

deft grail
#

try to understand it

velvet sierra
#

alr thanks

cosmic dagger
solemn bobcat
# velvet sierra I did not understand sorry. Can u guys explain like i'm 6 y.o and have brain iss...

.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.

toxic yoke
#

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.

hexed terrace
#

google -> unity how to detect mouse click

toxic yoke
#

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

hexed terrace
#

The answer is in the 2nd result of what I suggested to google

toxic yoke
#

can you send me the link please?

toxic yoke
#

thank you, that really didnt turn up for me

hexed terrace
#

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

toxic yoke
#

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

swift crag
#

You can then multiply that vector with a number to make it longer (so that you move faster)

velvet sierra
#

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

solemn bobcat
swift crag
#

oh wait, this is in the inspector :p

#

...is it?

#

let me see what you're doing either way

solemn bobcat
velvet sierra
swift crag
#

hm, that's working fine for me when I multi-edit two cubes' positions

rich adder
#

are you serious ?

#

you're still on this?

knotty ferry
#

ye man

#

I been 24h on this ;DDD

rich adder
#

didn't we like explain it dozens of times what solution was lol

knotty ferry
#

i tried the solutions but doesn't work

#

the time is working but it doesn't add seconds

rich adder
#

what exactly "doesnt work"

knotty ferry
#

it doesn't add time

solemn bobcat
rich adder
knotty ferry
rich adder
#

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

knotty ferry
#

im calling respawn, the script that i made with score it worked propertly but this doesn't work

solemn bobcat
rich adder
knotty ferry
#

i had debug i deleted it

rich adder
#

why

#

why would you delete them while debugging if its not working

knotty ferry
#

im gonna try again

velvet sierra
rich adder
# knotty ferry im gonna try again

for example

timerScript.timer += 20f; // Update the TimerScript.timer with the new value
Debug.Log($"Timer added {timerScript.timer}");

knotty ferry
rich adder
#

you have to be specific

knotty ferry
rich adder
#

then the method is not running

#

its that simple

knotty ferry
#

for u maybe it is mhm

rich adder
#

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

knotty ferry
rich adder
#

if (transform.position.y < -10f) // Assume obstacle falls below -10 units in Y position

#

....is this part even running at this point

knotty ferry
#

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

rich adder
#

you just said log isn't running

knotty ferry
knotty ferry
rich adder
#

jesus

knotty ferry
#

maria

rich adder
#

so when you said this it was made up or what

knotty ferry
#

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

rich adder
#

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```
knotty ferry
#

yes

#

u are correct

cosmic quail
#

so something is overwriting the timer's value?

rich adder
#

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

knotty ferry
#

it shows this but it doesn't add

rich adder
# knotty ferry 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}");```
rich adder
#

well there goes that

knotty ferry
#

it maybe adds but in game u don't see it

#

it should update the text ui

rich adder
#

yes, that part is true

#

are you sure you don't have more than 1 TimerScript script

knotty ferry
#

i have only 1 timerscript and other must be in obstacle controller

rich adder
#

how do you assign timerScript in Obstacle controller

rich adder
#

and this is on the same object as ObstacleController ?

#

can you show the ObstacleController's object inspector

knotty ferry
rich adder
knotty ferry
rich adder
#

is this object LevelManager ?

knotty ferry
#

no

rich adder
#

ok I see whats wrong then

knotty ferry
#

this is levelmanager

#

it updates time in diffrent scene

rich adder
#

ok look at your reference

#

Timer Script = LevelManager right ?

knotty ferry
#

yes

rich adder
#

great,now look

#
        timerScript = GetComponent<TimerScript>();```
#

what do you. think this line of code is doing

#

in ObstacleController

knotty ferry
#

getting reference

rich adder
#

from where

knotty ferry
#

to timerscript component my is attached to same object

rich adder
#

computers dont lie

knotty ferry
#

mhm

rich adder
#

hey Remember this

knotty ferry
#

yes i do remember

rich adder
#

ok so you know what the fix is now right ?

knotty ferry
#

;Dd

velvet sierra
#

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

rich adder
#

esp for character

eager spindle
#

rb.moveposition

#

what it does is checks if your object is hitting anything along the way when moving a position

eager spindle
#

rb.moveposition

#

you should look up what it does

#

you have a rigidbody right

rich adder
knotty ferry
rich adder
#

they both have methods which respects collider

rich adder
#

it will phase through walls

#

its meant for kinematics

rich adder
eager spindle
rich adder
#

remove the GetComponent line...

#

its literally grabbing a disabled script..

knotty ferry
#

now i get it

rich adder
#

if you assign components in inspector you should not use GetComponent

knotty ferry
#

After 20 hours

rich adder
#

as soon as game ran, it runs Start and it will run GetComponent

eager spindle
#

🎊

rich adder
#

lucky for you it did have it on the same gameobject so it didn't throw a null reference

willow scroll
knotty ferry
velvet sierra
# rich adder lucky for you it did have it on the same gameobject so it didn't throw a null re...

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
cosmic dagger
willow scroll
eager spindle
#

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?

knotty ferry
willow scroll
#

Well, you should be using Singletons for that

rich adder
#

I can't tell exactly type of game you're going for

rich adder
velvet sierra
#

2d top down. Character still moves when i no longer press button for some time like 1 or 2 sec

willow scroll
rich adder
velvet sierra
eager spindle
cosmic dagger
rich adder
velvet sierra
willow scroll
willow scroll
#

It doesn't make sense to be, the issue shouldn't be solved simply from that little change

rich adder
#

the smoothing was prob messing with their let go (probably feels laggy with smoothing)

cosmic dagger
velvet sierra
willow scroll
velvet sierra
#

Oh

willow scroll
#

I forgot about the GetAxis' smooth

knotty ferry
willow scroll
rich adder
#

could also use some kinda of multiplier already saved in each level

willow scroll
#

Of course, gotta have the tuples for all of them

knotty ferry
#

thanks

rich adder
#

might be too over the head for OP

#

lol

willow scroll
#

Looking fine to me.

willow scroll
willow scroll
#

||```cs
score += 20 * (1 / Regex.Match(SceneManager.GetActiveScene().name, @"\d+"));

#

Whatever. There is no formula

plush oxide
#

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

rich adder
#

why not do everything inside coroutine

plush oxide
#

everything like the keycode stuff as well?

rich adder
#

You could

#

like use something like WaitUntil

plush oxide
#

does wait for seconds not work here

wintry quarry
#

Or just do it all in Update

plush oxide
rich adder
#

true

#

just get rid of coroutine altogether

plush oxide
#

alrigh

rich adder
#

use update with a timer

deft grail
#

the bool does nothing

plush oxide
#

time.time then

plush oxide
rich adder
#

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
plush oxide
#

interesting

#

what does the => do

rich adder
#

lambda function in this case

plush oxide
#

what does that mean

wintry quarry
#

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

plush oxide
#

i see

plush oxide
#

okay ill read that

rich adder
#

but yeah just stick to Update if thats easier for you

#

less alloc

plush oxide
plush oxide
#

but I think I got the general idea of how to fix this

rich adder
plush oxide
#

i see

#

thanks for both of your help though

#

🔥

onyx tusk
#

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?

molten dock
#

if (Input.GetMouseButtonDown(0)) { }

swift crag
#

you're getting into platform-specific code

#

but maybe I'm just misunderstanding your question

onyx tusk
deft grail
#

is the script on an activate game object and is this code in Update?

onyx tusk
swift crag
#

use Input.GetMouseButton if you want to know if it's up or down, full stop

onyx tusk
deft grail
rich adder
onyx tusk
rich adder
#

Why would you use that if you want to be called from anywhere

onyx tusk
rich adder
#

we know, as Fen suggested you should use GetMouseButton but inside Update (Inputs are typically "polled" here)

rich adder
#

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

violet glacier
#

How do I change the scale of game objects in my world space to the same scale as canvas ui?

onyx tusk
swift crag
#

i have no idea what code you actually wrote

#

show it.

brave robin
violet glacier
# rich adder whats the usecase ?

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.

swift crag
#

oh, you mean you used Input.GetMouseButton inside of the OnMouseEnter method

#

that sounds reasonable enough

rich adder
#

the timing would have to be insane

onyx tusk
# swift crag show it.
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*/
  }
};```
rich adder
#

not sure what UI has to do with anything

brave robin
violet glacier
swift crag
#

the camera is going to render exactly the same (whether it's perspective or orthographic)

#

unless these are actually images on a canvas

violet glacier
swift crag
#

are these objects images on a canvas?

violet glacier
#

I made this infographic

swift crag
#

ah, you're talking about changing the aspect ratio

#

Is this a perspective camera or an orthographic camera?

violet glacier
swift crag
#

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
violet glacier
#

Ok thanks, I will look into it🙂

swift crag
#

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

plush oxide
#

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

swift crag
#

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

hexed terrace
swift crag
#

oh

swift crag
#

i had a moment

plush oxide
swift crag
#

💥

plush oxide
#

what if I put the first if statement after the other one

#

then would it work

swift crag
#

This looks fine, then. It will spawn one object and set cooldown to 2

#

pressing D within 2 seconds should do nothing

brave robin
swift crag
#

it doesnt spawn 1 and spawns more

do you mean that hitting D spawns many objects instantly?

plush oxide
#

no, that happened earlier, now It duplicates whatever is on scene

#

i shouldve specified

#

my bad chat

swift crag
#

i don't know what "whatever is on scene" means

plush oxide
#

whatever capsules are on scene

brave robin
#

Is your script on the object that you're instantiating?

plush oxide
#

it duplicates them

swift crag
plush oxide
#

is that the problem

brave robin
#

tada!

plush oxide
#

interesting

#

i never thought that was a problem

brave robin
#

Well yes, because now all the new ones are also listening for D and then making more

plush oxide
#

OH

#

i see

#

do I just put the script on something else

brave robin
#

Yeah, put it on something that's sitting in the scene and handles that one task

plush oxide
#

alright , ill try that and message here again

brave robin
#

Its pretty common for a scene to have a bunch of game objects that just run logic and have no mesh or sprite

swift crag
#

most of my game objects have no physical presence

plush oxide
#

thats kinda clean guys

#

it works

wind raptor
#

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"?

swift crag
#

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?

brave robin
#

It might be that what they need is a singleton, or static class, if they want global access to something

#

But edepends on usecase

raven ferry
#

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.

swift crag
#

a canvas in either of the "Screen Space" modes will work

raven ferry
#

ah! okay!

swift crag
#

Screen Space - Overlay draws directly onto the screen, and Screen Space - Camera follows the camera around

wind raptor
swift crag
#

There are partial classes

#

if you literally just want to break a single class's definition up into several parts

swift crag
#
public partial class Foo {
  public int one;
}

public partial class Foo {
  public int two;
}
wind raptor
#

huh

swift crag
#

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

wind raptor
#

Does that work, with Monobehaviours?

swift crag
#

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

brave robin
#

I also avoid partial classes. I'd rather refactor the massive class into smaller utility ones that the main one can use

swift crag
#

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

brave robin
#

partial is also sometimes used when multiple coders are involved, but that's better served with source control apps

wind raptor
#

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.

swift crag
#

If you use a few fields or properties from another object very regularly, you could do something like this: