#💻┃code-beginner

1 messages · Page 804 of 1

stuck parrot
#

how so, WASD or left stick is walking direction, space bar or A button is jump, mouse or right stick is look around. how is that not standardized?

vital barn
#

Programming is creative work

naive pawn
sour fulcrum
#

What is walking
What is jumping
What is looking

stuck parrot
naive pawn
#

@sour fulcrum what do you mean by that reaction? i thought that was marking crossposted questions thinkies

naive pawn
#

oh, ive usually seen 👍 💯 this ☝️ etc for that

sour fulcrum
#

They share fundamentals but games need to be specific

#

Code defines these specifics

stuck parrot
naive pawn
# stuck parrot come on, you tell me after 40 years or so, game engines need code to know what j...

there are several, several ways to implement jumping, depending on the game.

some games don't have jumping at all.
some have force-based jumping, simulating a real-life parabolic arc.
some have more snappy jumps, for more precision in parkouring/platforming.
some games let you control the height by holding the button for longer, some don't.
some games have double-jumps, some don't.
some games have wall jumps, some don't.
some games have coyote time or input buffering, some don't.
some games make you move faster when you jump, some don't.
some games give you less control in the air, some don't.
some games have hovering or flying, some don't.

naive pawn
sour fulcrum
#

coyote time, physics potential, wave dashing type stuff, sliding, diagonal support etc etc

stuck parrot
sour fulcrum
#

Sure

naive pawn
#

if you're starting out, sure

vital barn
naive pawn
#

as you get more experience, you can adapt resources that are less specific

#

you might be able to adapt results from googling "mario bros jump physics" into your game

stuck parrot
naive pawn
#

you have to design and implement the mechanics. that's what coding is for

#

movement is one such mechanic

#

model the characters, the environment, create the cutstenes, come up with a story.
if you don't have interactivity, this is just a movie or a visual novel

vital barn
#

Well, at the stage of conception

#

Well, the pc

naive pawn
#

previously, games generally existed mainly in text format
thonk wouldn't the first video games be like, arcade games?

stuck parrot
naive pawn
naive pawn
#

consider how minecraft, terraria, pubg, and apex legends handle item pickups

#

or how hollow knight, minecraft, terraria, skyrim handle npc interaction

#

if you want to follow some particular well-known style, then you could probably find existing assets/resources to do so
but unity can't cater to everyone simultaneously

stuck parrot
# naive pawn that wouldn't work, because every game does that differently

maybe im just to dumb to understand it yet but for the NPC talking example. how does every game doest it differently? you walk twards an PPC which is a game object. if you are in an certain radius and press a specific key, they play an animation, stop your movement and display a text or sound. thats the same in every game I can think of

sour fulcrum
#

How those things are specifically done are things programmers want control over

#

What you want is totally valid, it’s just not really unity

#

Dreams on ps5 is something a little closer

naive pawn
sour fulcrum
#

Not to mention saving

naive pawn
#

the overall concept is the same, yes. it's the details that are different, it's the details that you want to control

stuck parrot
stuck parrot
naive pawn
#

start by disregarding code entirely - consider the design
see how other games do it, see what feels right for your game
you would identify what elements you need, then you would design how they lay out, and then you'd get to implementing it

#

I can code the pseudo code
you're already a good chunk of the way there then
have some patience and do it yourself, that way you can actually learn

stuck parrot
sour fulcrum
naive pawn
stuck parrot
naive pawn
#

nah i was vague there, that's kinda on me

naive pawn
#

if you see someone doing it without researching, that's because they've done it before
or if you see someone doing it without designing, that's because they have enough experience to do it in their head for that task

#

research and design are crucial to giving yourself an easier time

stuck parrot
#

would you sidgest starting bigger with what I have in mind (recreating the first level of super mario 64) and expanding my game from there? or starting low with a 2d platformer or stuff like that

sour fulcrum
#

Small as possible

#

Like tic tac toe

naive pawn
#

it's easiest to learn 1 thing at a time, but often that's not possible. if you minimize the things you have to figure out at the same time, that's going to be easier

#

start very small, and once you understand and are comfortable with the tools introduced there, move on to using more tools

vital barn
naive pawn
#

(tools being components, features, different chunks of logic, etc)

twin pivot
stuck parrot
naive pawn
#

plenty, probably

#

but generally you want more customization than that. this is more of a physics demonstration

#

the source code for that is available btw

vital barn
queen adder
#

Happy Sunday to everyone! Im learning lifecycles which Is overdue and is very important I think. My question is do I initialize self contained variables in the Awake method or OnEnable method? Lets say for example I will reuse this object after death and when its going to be enabled again its health will restore to 100, so health initialization in Awake isnt quite needed I suppose since when the object will be enabled its health value will be 100 and when its going to be disabled and reenabled later health will be reinstated to 100 once again. But lets say the object dies once and is not reset again, where does it make sense to initialize the health variable? I read the self component references and variables are best to be initialized in Awake? Want to hear some explanation from actual people rather a GPT or a documentation. Thanks

#

⁨```cs
public int health;

private void Awake()
{
    health = 100;
    Debug.Log("Object is Awake!");
}

private void OnEnable()
{
    health = 100;
    Debug.Log("Object is enabled! Current health is " + health);
}

private void Start()
{
    Debug.Log("Object is starting to die!");
}

private void OnDisable()
{
    Debug.Log("Object has died!");
}
#

And this is a simple Coroutine im running in a " game manager " object.

#

⁨```cs
private IEnumerator Test()
{
if (!playerController)
{
yield break;
}

    yield return new WaitForSeconds(5f);
    playerController.enabled = true;

    for (int i = 0; i < 10; i++)
    {
        yield return new WaitForSeconds(1f);
        playerController.health -= 10;
        print("Player health: " + playerController.health);
    }
    playerController.enabled = false;
    yield return new WaitForSeconds(5f);
    playerController.enabled = true;
}
#

Just to view the life cycles in console

#

What I understood the most is Awake and OnEnable is best used to initialize self contained variables and references and only then start cross referencing other scripts in the Start method once the Awake and OnEnable are done for all game objects.

#

So Im just wondering where is the best place to initialize variables used in the same script, or it just depends how is it used?

naive pawn
#

Awake is only going to run once, so if you need reuse the object and restore some state, Awake doesn't make sense

queen adder
queen adder
#

or like reference other same object components like transform etc.

naive pawn
#

Awake and Start are for initializing stuff that make the component usable, they run once
OnDestroy similarly runs once, for cleaning up stuff that was done in Awake or throughout the entire existance of the component

OnEnable would be for setting up the object when it, well, becomes enabled and active
OnDisable would be for cleaning up stuff that was done in OnEnable or throughout the active operation of the component

naive pawn
queen adder
naive pawn
#

if everything uses the assumption of being resettable, then no need to make an exception in this one case because it's "unneeded"

queen adder
#

so both onenable and awake is fine to initialize self contained variables, just depends how the object will be used

naive pawn
#

i miswrote in the previous message, should be "how the object can be used"

#

not necessarily only how it's currently being used

queen adder
#

And lets say I create references to other scripts in "Start" and the object gets disabled "not destroyed" will it still have that reference in memory even if its disabled and would be re-enabled again?

#

only when it gets destroyed they lose the references?

tender mirage
#

If you wanna save memory or split your games into sections without consuming memory, you'll have to destroy and instantiate objects appropriately.

queen adder
#

Thank you. So enabling / disabling rather than destroying and instantiating objects makes more sense

#

this is close to object pooling i think? Im yet to learn that concept as well

#

but I will stop asking here, since this place is more for coding questions

#

I got the idea

cosmic dagger
#

Likewise, I'd have a Deinitialize or some type of reset method to call before returning it to the pool . . .

ivory bobcat
rich adder
#

!collab

radiant voidBOT
# rich adder !collab

:loudspeaker: Collaborating and Job Posting

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

rich adder
#

sounds like a bot

median hatch
#

⁨```cs
using System.Collections;
using UnityEngine;

public class HoverBullet : BaseBullet
{
[SerializeField] public GameObject enemy = null;

[SerializeField] public bool isHovering;

[SerializeField] Vector3 moveDir;

// Start is called once before the first execution of Update after the MonoBehaviour is created
protected override void Start()
{
    base.Start();

    moveDir = transform.forward;
}

void FixedUpdate()
{
    if (!isHovering)
    {
        transform.position += moveDir * bulletSpeed * Time.fixedDeltaTime;    
    } else
    {
        transform.position = Vector3.MoveTowards(transform.position, enemy.transform.position, 2f * Time.fixedDeltaTime);
    }
}

}


why does my bullet immediately teleport to the enemy? i want it to follow him instead
cosmic dagger
median hatch
median hatch
cosmic dagger
median hatch
#

ill try using a rigidbody instead

cosmic dagger
# median hatch isHovering

so, the MoveTowards code is running? how are you doing collisions? if you're using colliders, you shouldn't move using transform.position . . .

#

use velocity or force to move the bullet . . .

median hatch
median hatch
silver fern
#

what's a good way of referring to prefabs in a dictionary without instantiating them?

#

just store the path to each file in a string?

runic lance
silver fern
runic lance
silver fern
#

so I wanted to store the references in a dictionary with an id to make it easier

runic lance
#

this seems to be a pretty good use case for addressables any way, you just need to store an asset reference and forward it however you want, no need to deal with path strings

silver fern
#

ah yes that looks like it'll do the trick, thanks

spare herald
#

hi im having an issue with unity version control so basically i made an alt account owner and tried to commit code but it says i dont have permissions even though im an owner of the project

rich adder
#

do yourself a favor and save unecessary headaches and use Git. UVC is a dump

rich adder
#

Git, not to be confused with Github

spare herald
#

we need to make a group project and uvc was the only thing which wasnt blocked

spare herald
#

ik

solar hill
#

iirc you can upload/commit to github directly from the browser

#

unless they blocked the site itself

spare herald
#

they did

solar hill
#

what is with these schools man

#

and blocking git

silver fern
#

what about codeberg or gitlab

rich adder
#

how does a school block the git software

solar hill
spare herald
#

yeah

solar hill
#

even git

rich adder
spare herald
#

it just says i have to request permission to download smth

solar hill
#

honestly at that point i would just do manual back ups lol

#

uvc is that annoying

rich adder
#

yeah idk that thing is always bugged

#

you might have better luck asking on Unity Discussions site and maybe those VC devs might see

spare herald
#

ahh alright thanks

rich adder
#

whatever is left from all the layoffs

solar hill
grand snow
#

/r/totallynotbots moment

silver fern
#

I suppose I don't even need the dictionary if I can just use the addressable address string directly

#

but then its string comparison again

#

I suppose there's no way around it

silver fern
grand snow
silver fern
#

I see

#

yeah I was going to make a dictionary but that actually makes it worse

#

vs. using just the character name as address string

grand snow
# silver fern I see

A great way for beginners is to use scriptable objects to store configuration for stuff like this:
⁨⁨```cs
public class CharacterConfig : ScriptableObject
{
public AssetReferenceGameObject prefab;
public int health;
public string displayName;
}


You can load many into a dictionary:
⁨⁨```cs
Dictionary<string, CharacterConfig> characterConfigs;
//...
//Load them all from a resources folder and add to a dictionary
var assets = Resources.LoadAll<CharacterConfig>("CharacterConfigs/");
characterConfigs = new(assets.Length);
foreach(var asset in assets)
{
  characterConfigs.Add(asset.name, asset);
}
```⁩⁩
silver fern
#

I see, thanks

#

I'll try and use that

grand snow
obsidian plaza
#

Not sure if this is even possible to fix but whenever I move in my first person camera while fixating on an object, I can kind of see the object vibrate instead of move smoothly. I know this is kind of an issue with every first person game but it feels a little strong in my project.

My camera is a child of my player although I think thats irrelevant because the actual camera moving looks fine, but looking around with my mouse is the issue especially when combined with moving around. Here is my camera movement code that is being called in update:
⁨⁨⁨```C#
Vector2 mouseDelta = Mouse.current.delta.ReadValue();
float mouseX = mouseDelta.x * mouseSensitivity;
float mouseY = mouseDelta.y * mouseSensitivity;

    //rotate body left/right
    transform.Rotate(Vector3.up * mouseX);

    //rotate camera up/down
    xRotation -= mouseY;
    xRotation = Mathf.Clamp(xRotation, -maxLookAngle, maxLookAngle);

    if (playerCamera != null)
    {
        playerCamera.transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
    }```⁩⁩⁩
grand snow
#

Where is this executed? Update?

obsidian plaza
#

yes

grand snow
#

How is the player moved then, physics?

obsidian plaza
#

yea linearvelocity

grand snow
#

Do you have interpolation enabled?

obsidian plaza
#

yes

grand snow
#

You probably should be rotating the rigid body with physics too or you need to lock physics rotation

#

You can also try assigning to rigidbody.rotation instead if doing this

#

Example of some basic movement I did a while ago:
⁨```cs
private void FixedUpdate()
{
//Movement
Vector3 input = inputs.gameplay.move.ReadValue<Vector2>();

    //Change speed
    input *= MoveSpeed / Time.fixedDeltaTime;

    //Make local
    input = rigidBody.rotation * new Vector3(input.x, 0f, input.y);

    rigidBody.AddForce(input, ForceMode.Force);
#

I rotated in late update:
rigidBody.rotation *= Quaternion.Euler(0f, lookInput.x, 0f);

obsidian plaza
#

hmm ok i have some developments

#

i did the following code and it COMPLETELY got rid of the vibrating, but now general mouse movement feels slightly choppy as if its like 30fps
⁨```C#
if (rb != null)
{
Quaternion yaw = Quaternion.Euler(0f, mouseX, 0f);
rb.rotation = rb.rotation * yaw;
}
else
{
transform.Rotate(Vector3.up * mouseX);
}

#

i can try fixed update again although that wasnt good before

strange jasper
#

Hey, im making a proceedural spider leg system and im confused on how instead of lerping the legs, they would start at the starting position, and go to the end position while lifting up in the process like a spider, and if anything in my code is badly optimised?

queen adder
grand snow
#

Why not?

naive pawn
strange jasper
grand snow
#

hmm no

naive pawn
#

no, that's not relevant

grand snow
#

For important inputs like jumping yes its not a good idea as we may miss them

strange jasper
#

ohh okay

obsidian plaza
#

it will only reads the movement every so often which is a longer stretch of time than your FPS so it feels like lower fps no?

naive pawn
#

input is framebound, it gets updated every frame
detecting the rising or falling edge of an input should be done on the update loop
but for getting the current value of an input, it can be done anywhere, just that it'll be updated in the update loop

grand snow
#

Thats why I had this in LateUpdate
⁨```cs
if(!shouldJump)
{
shouldJump |= inputs.gameplay.jump.WasPressedThisFrame();
}

#

Read the input more frequently to then use in FixedUpdate to add force

naive pawn
obsidian plaza
#

yea i realized that

naive pawn
#

so yes, there's some delay, but just moving the input wouldn't change anything

obsidian plaza
#

which is why it still feels bad in update

#

but it does look better so im torn what to do

naive pawn
#

yeah personally i like having input in update for organizational reasons, but no technical issue with this

queen adder
# naive pawn for pressing/releasing edges sure, but for reading values it's fine tbh

I replicated my input delay problem I had last week, where sometimes the rigidbody object moved with delays and saw that I was reading my Input in the same method where the movement was applied inside FixedUpdate. So my thought process was 0.005s is four times faster than 0.02s of the fixed time step, I moved the input to update and it started working fine?

#

Maybe a coincidence

naive pawn
#

could be, but (without any further info) my next best guess would be you were moving with the transform

queen adder
#

no was moving the whole rigidbody.position like advised here too ^^

naive pawn
#

oh hm 🤔 that's meant to be a teleport without simulating physics, maybe that gets applied immediately?

obsidian plaza
#

is it not more affected by physics lag if in fixed or no?

queen adder
#

⁨```cs
private void FixedUpdate()
{
Move();
}

private void Move()
{
Vector2 verticalInput = move.action.ReadValue<Vector2>();

Vector2 finalInput = verticalInput * (movementSpeed * Time.fixedDeltaTime);

Vector2 targetPosition = myRigidbody.position + finalInput;

targetPosition.y = Mathf.Clamp(targetPosition.y, -yAxisBoundary, yAxisBoundary);

myRigidbody.MovePosition(targetPosition);

}

grand snow
naive pawn
#

since the docs do mention using this to help with updating the physics scene

naive pawn
naive pawn
queen adder
naive pawn
#

.rotation = is a teleport, MoveRotation is a sweep

obsidian plaza
naive pawn
naive pawn
queen adder
#

⁨```cs
myRigidbody.MovePosition(targetPosition);

#

thats what Im moving with

naive pawn
obsidian plaza
naive pawn
#

yeah but what lag are you referring to by "physics lag"

grand snow
obsidian plaza
#

idkkk like the fixed update tick coming late

queen adder
grand snow
#

Its either change rotation without physics but update physics or rotate with physics and interpolation

naive pawn
queen adder
#

I moved Input to Update and I didnt get the same problem

#

But I have to say I changed the batteries to my keyboard that same time, so that couldve been the culprit too haha

naive pawn
#

yeah those seem unrelated to me

#

moving the input and fixing the lag, i mean

grand snow
#

FixedUpdate executes on the main thread when enough time has passed and we want to update physics so reading translation movement input in update/fixed makes no difference.

naive pawn
#

another option couldve been that the input was being read incorrectly, maybe after the rb move

queen adder
#

i will try moving it back to Fixed Update again, as now Im thinking about it that input should be better off in sync with the rigidbody

grand snow
#

If we just want to get the current state of WASD/controller stick for physics movment then Update/FixedUpdate will do the same because both get executed on the frame it happens on the same thread.

queen adder
grand snow
#

It will be better because fixed update may get executed a tad sooner because more frames means better precision to hit the desired physics update time step.

hallow bough
#

Gurble

queen adder
#

Isnt it reversed? More FPS means more Update to FixedUpdate calls.

#

Update

#

Update

#

Update

#

FixedUpdate

grand snow
#

no

queen adder
#

Update

grand snow
#

it would be:
Update
Update
Update + FixedUpdate

queen adder
#

Which is bad?

grand snow
#

not sure but what function we read input from didnt cause that did it?

#

Input system also polls devices at a fixed rate too so that would also affect the input data we read

queen adder
#

my beginner expertise ends here ^^ need to do further studying and experimenting

grand snow
#

yea it can be confusing but me and others are here to offer advice again in future

queen adder
#

Just trying to think with my own head while im learning

#

LateUpdate for camera movement and rotations makes sense to wait for Update to finish moving the object itself first then fire the lateUpdate for the camera to move to the last position. I had jittery camera movement before when I had it follow the "player" in Update loop.

naive pawn
grand snow
#

LateUpdate is very useful. If we want to follow a transform (e.g. UI) then thats the place for that too.

strange jasper
#

Hey, im making a procedural spider leg system and I'm confused on how instead of lerping the legs, they would start at the starting position, and go to the end position while lifting up in the process like a spider?

⁨```cs
void UpdateLegPosition()
{
CalculateLegTargets();

    for (int i = 0; i < LegIKTransforms.Length; i++)
    {
        float step = legLerpSpeed * Time.deltaTime;
        LegIKTransforms[i].transform.position = Vector3.MoveTowards(
            LegIKTransforms[i].transform.position,
            LegTarget[i].position,
            step
        );

        //LegIKTransforms[i].transform.position = LegTarget[i].position;
    }
}
ivory bobcat
#

I'm assuming the problem is that everything happens instantly

queen adder
naive pawn
#

in the same vein as the camera following some target, sometimes you want non-child UI to follow some target

strange jasper
queen adder
naive pawn
#

sure, in my case i have tutorial text inside a level where i want it to follow a player around

grand snow
#

If the element is actually in screen UI then we need to do WorldToScreen conversion

finite flower
naive pawn
queen adder
ivory bobcat
strange jasper
#

oh wait i wrote that at 5am i thought i was using lerp

grand snow
ivory bobcat
#

If you want non linear motion like the image shown, you could probably use slerp or some other non linear interpolation

ivory bobcat
strange jasper
#

Yeah

naive pawn
#

@strange jasper on a side note, i'd also recommend opening some document in draw.io/powerpoint/canva/miro/etc and try drawing out different scenarios, and see what you'd want for each scenario, and then you can find a solution that matches that

#

maybe a parabola doesn't look nice with a short distance for example, you could then maybe try a circular arc instead

#

would help you figure out what constraints and inputs you want too, which would make the implemenation easier

strange jasper
finite flower
#

I have a question that's probably better for general, but I'm not really sure how to ask for what I want.

#

I'm trying to figure out how to transition from walking up to a wall, to climbing that wall and vice versa

#

I'm stuck with how to switch between the ground movement and the climbing movement and how to do that without locking the player to either the ground or wall and needing them to jump to either.

naive pawn
#

in terms of design/interaction, or implementation?

finite flower
#

implementation

#

i have the climbing movement and walking movement, but idk how to transition them in code

naive pawn
finite flower
naive pawn
#

it's kinda sounding like you're more stuck on design/interaction

finite flower
naive pawn
#

and what should the intended flow be?

finite flower
#

If I'm climbing down the wall, I should start walking when I hit the ground, or if I walk up to a wall, I should be able to just start climbing.

#

It should be a smooth transition. I shouldn't have to jump to get it to work

naive pawn
#

ah, ok. i misunderstood what you were trying to say in your initial message

#

well, start with design, you'd want to detect the ground (when climbing)/a wall (when walking) within some distance and direction

#

could probably use raycasts for that

finite flower
#

rn I'm using a spherecast for both. A sphere at the players feet detecting the ground and one directly in front of their center detecting walls.

naive pawn
#

both always active?

finite flower
#

The ground check is always active and the wall check is only active when the player is moving

naive pawn
#

The ground check is always active
well then you'd never be able to leave the ground

barren iris
#

hey! thanks for this I just managed to figure out how to convert my inputs to the rb movement but it still goes through the object (whilst its in the bounds of the object it shakes about) was just wondering if you knew a method as the last line of this message seems promising haha.

naive pawn
#

i'm about to go so can't look into this further, but i'd guess something like this might help?

in grounded state:
  if walking forwards and raycast hit wall:
    -> climbing
in climbing state:
  if going down and raycast hit floor:
    -> walking
```so it only transitions with player input
grand snow
barren iris
#

of course one sec!

strange jasper
#

im sure ive fucked it up

⁨```cs

LegIKTransforms[i].transform.position = Vector3.Slerp(
LegIKTransforms[i].transform.position,
LegTarget[i].position,
stepHeight
);

magic cape
#

where do i even start?

strange jasper
#

its 0.5

timber tide
#

Docs go over it

#

It's not a rate

strange jasper
#

wdym?

timber tide
#

Read the docs

grand snow
#

Lerp abuse!

strange jasper
grand snow
#

Linear interpolation is not to be used to "move towards some value by a constant rate"

strange jasper
#

im trying to get it to move from one point to another in an arc motion

grand snow
#

Vector3 Move towards can do this however

#

Then some function to do this using sin should do

timber tide
#

oh you'd need to sample a bunch of points if you want to do it this way then

#

curve or sine is an idea too yea

strange jasper
#

like in what way

timber tide
#

animation curve gives you a bit more editor control for big steppy

strange jasper
#

thank you :)

timber tide
#

Ideally just make the curve normalize from 0-1 too

strange jasper
#

didnt know itd be this hard to make a transform move in an arc trajectory kekwait

timber tide
#

Throw me the code you're moving on the x/z axis

strange jasper
#

⁨```cs
void UpdateLegPosition()
{
CalculateLegTargets();

    for (int i = 0; i < LegIKTransforms.Length; i++)
    {
        float t = Time.time * legLerpSpeed;
        float y = Curve.Evaluate(t);

        Vector3 currentPos = LegIKTransforms[i].transform.position;

        LegIKTransforms[i].transform.position = currentPos + new Vector3(0, y * stepHeight, 0);
    }
}

i dont think im doing something right to be honest
timber tide
#

⁨```cs
public AnimationCurve Curve; //0 to 1
public float HeightMulti = 3f;

public void MoveLeg(Vector3 target, float duration)
{
StopAllCoroutines()
StartCoroutine(MoveRoutine(target, duration));
}

IEnumerator MoveRoutine(Vector3 target, float duration)
{
Vector3 start = transform.position;
Vector3 end = target;

float elapsed = 0f;

while (elapsed < duration)
{
    elapsed += Time.deltaTime;
    float t = Mathf.Clamp01(elapsed / duration);
    float height = Curve.Evaluate(t) * HeightMulti;

    Vector3 pos = Vector3.Lerp(start, end, t);
    pos.y += height;

    transform.position = pos;

    yield return null;
}

transform.position = end;

}

Something like that. The only problem I'm thinking of is if the coroutine can get interupted. Haven't really done one of these projects yet
#

Actually duration wouldnt make too much sense if you want to step closer. So you want to make a rate from distance and a speed

finite flower
#

how would I write a check that sees if a boolean becomes true?

strange jasper
strange jasper
# timber tide ⁨```cs public AnimationCurve Curve; //0 to 1 public float HeightMulti = 3f; pub...

⁨```cs
void Update()
{
CalculateLegTargets();

    for (int i = 0; i < LegIKTransforms.Length; i++)
    {
        float distance = Vector3.Distance(
            LegIKTransforms[i].transform.position,
            LegTarget[i].position
        );

        if (distance > legThresold) 
        {
            MoveLeg();
        }
    }
}

public void MoveLeg()
{
    StartCoroutine(UpdateLegPosition());
}

IEnumerator UpdateLegPosition()
{
    CalculateLegTargets();

    for (int i = 0; i < LegIKTransforms.Length; i++)
    {
        Vector3 start = LegIKTransforms[i].transform.position;
        Vector3 end = LegTarget[i].position;

        float elapsed = 0f;

        while (elapsed < legLerpSpeed)
        {
            elapsed += Time.deltaTime;
            float t = Mathf.Clamp01(elapsed / legLerpSpeed);
            float height = curve.Evaluate(t) * stepHeight;

            Vector3 pos = Vector3.Lerp(start, end, t);
            pos.y += height;

            LegIKTransforms[i].transform.position = pos;
            
            yield return null;
        }

        LegIKTransforms[i].transform.position = end;
    }
}

not entirely sure whats gone wrong
timber tide
#

Hmm, actually I am just appending a height but I should be sampling from the base height

#

Actually, it does look correct. I have to try it out when I get home.

strange jasper
timber tide
#

Really looks fine to me. I'd double check if it's something setting your values elsewhere

#

Oh, remove your update

#

Shoudl just be calling the coroutine

#

Oh, ok maybe you're calling the coroutine multiple times

#

Like, for testing purposes just throw what I gave you onto a random gameobject and make sure that works

strange jasper
timber tide
#

Ye, this way should work fine assuming that the leg always completes the destination, but otherwise you may run into issues if you need to interupt them which will require more logic.

vapid egret
#

I have a C# question. I have a few void methods that are going to be called in the ⁨Update()⁩ method of a MonoScript. Should they be positioned before or after ⁨Update()⁩? Does it matter?

grand snow
#

makes no difference

vapid egret
#

Thank you. For future reference are any of the other built in methods like ⁨LateUpdate()⁩ or ⁨OnDisable()⁩ sensitive to void method positioning?

grand snow
solar hill
#

c# is a compiled language

#

the entire class is read first

#

and then it starts to care about method calls

grand snow
#

It may in C and C++ but thats due to how that gets compiled compared to more modern languages

solar hill
#

in python for example the order does start mattering

#

because its not compiled but interpreted or whatever

vapid egret
#

Oh that's cool! I come from Java/Typescript where we have to worry about that sort of thing. Good to know!

solar hill
#

🤔 im like 99% sure that java is also compiled

#

and that positioning does not matter

vapid egret
#

I meant JavaScript/TypeScript

solar hill
#

ah

keen dew
#

The order doesn't matter there either

solar hill
#

you sure? im pretty sure js is interpreted and not compiled

#

nvm i checked

#

it matters for function expressions

#

but not declarations

keen dew
#

That doesn't really factor into it, the interpreter parses the entire code before executing it

vapid egret
#

It goes line by line in function declarations unless you're using async

grand snow
#

in c and cpp it matters because compilation is done in a single pass (which is why forward declaring is possible and sometimes needed)

#

c# does multiple passes to avoid the issue

keen dew
#

Function declarations are hoisted in JS

solar hill
#

yes and expressions are not

timber tide
#

there's people who dislike headers

keen dew
#

I mean it's exactly the same in C#, class methods in JS -> order doesn't matter, expressions (delegates/lambdas) -> order matters

grand snow
#

haha well it solves a real problem, defining symbols ahead of time

#

same for forward declaring. Its "trust me compiler this will get defined soon 🙏 "

strange jasper
#

since the behaviour is obviously different i think your logic does work

timber tide
#

the problem is that if the leg starts in the air then you arc from the current position mostly

#

you can interupt it fine, but you need to figure what the idea is to reposition the leg mid transition

#

in that case you may not want a coroutine and just reuse the current progress in update

finite flower
strange jasper
timber tide
#

sure, but logic needs to change a bit since you cant yield from update like that

strange jasper
#

what do i do?

strange jasper
vapid egret
#

What's everyone's favorite keyboard shortcuts in Visual Studio?

wintry quarry
#

Alt + F4

vital barn
#

Alt + hold power button

tender mirage
#

Sorry. I can’t have a favorite child.

north jolt
#

Is there something better than visual studio

grand snow
teal viper
north jolt
#

Idk I’m a complete beginner, just wanted to know if there is better options

strange jasper
#

Say I have 6 vectors, how would i average those out to get a rotation of an object?

ivory bobcat
strange jasper
#

Yes, I'm trying to calculate body position for a spider based on where the leg targets are, you probably saw it earlier

ivory bobcat
#

Average would just have to add up the values and divide by the number of values

#

If you're referring to the ⁨centroid⁩, you can simply look that up.

strange jasper
#

ill try averaging it and ill try centroids, thank you :)

#

yeah ill try centroids

hybrid tapir
#

do the unity devs ever plan to add support for custom enum parameters and more than one parameter for unity events? theres soooo much more i could do easily if i didnt have to find a workaround for everything not supporting the useful stuff.

#

i could make the 160 wrapper functions, but would the dropdown even support that?

sour fulcrum
#

Probably not no

still arrow
#

hey im new here and need some info, i have the go from a DEV to mod the new game and i have problem finding the right tools. the game is Burglin' Gnomes

slender nymph
#

you'd have to ask in that game's modding community, we can't help with modding here

still arrow
#

oooh thanks

strange jasper
#

Kinda stuck here, I have a spider with six legs, and it has six IK targets, I want to use centroids to calculate the bodys rotation using the IK targets but I'm not too sure how, right now it's like 2, but I want it to be like 1

#

better explanation

ivory bobcat
#

Where distance would be how far away you ought to be from the floor (the average of your leg heights relative to the surface of the floor)

strange jasper
ivory bobcat
strange jasper
#

What if I want more legs

ivory bobcat
#

You'd have to accommodate for whatever you're wanting to do

strange jasper
#

well make a spider

ivory bobcat
tranquil forge
#

so only quaternion have slerp right and using lerp for this will have a built in dampening effect and slerp isnt? is this how i should use lerp and slerp? damp and no damp?

naive pawn
#

can't you also slerp direction vectors

#

damping isn't relevant

polar acorn
#

Slerp will treat the values as directions. Lerp will treat them as numbers. Slerp will get you a value between two directions, the point some percent of the way along an arc between the two directions on a unit sphere. Lerp will get you that point along a line drawn between the two

naive pawn
#

lerp goes in a direct euclidian line, slerp goes along the surface of a sphere/circle

tranquil forge
slender nymph
#

are you only looking at Vector2?

tranquil forge
slender nymph
#

because Vector3.Slerp absolutely exists

polar acorn
#

Neither of them even have a concept of damping, it just gets you a value some percent of the way between two others

slender nymph
#

literally the only difference between the two is spherical (slerp) vs linear (lerp)

naive pawn
#

sl is spherical linear

#

the linear means the output changes linearly, not that it's a straight line

tranquil forge
#

why the first lerp (linear) have the damp thing

polar acorn
naive pawn
#

it shouldn't

#

Quaternion has a lerp?

tranquil forge
#

rotate with the first lerp slow down when near 180 and speed up again

polar acorn
#

One of them will be linear. One of them will be spherical. As demonstrated in the gif

naive pawn
#

oh, yeah

#

guys the difference is not spherical vs linear, it's spherical vs direct notlikethis

#

they're both linear

polar acorn
#

Well, one of them is eculidian linear, one of them is non-euclidian linear

#

but that's a bit more confusing to explain

naive pawn
#

they're both linearly proportional

#

the "linear" is about the function, not the geometric result

strange jasper
#

How would I make this core rotate based on the position of the legs? kinda stuck and im not really sure what to do or what steps to take

slender nymph
#

sure, but when explaining it to someone who clearly can't tell the difference between the two, is it not just easier to point out the "linear" vs "spherical" (even though the latter is still linear, just in a different way)

naive pawn
#

thonk i feel like it misleads about the l in slerp but fair enough

polar acorn
#

The most important thing is to impart that it is not "Do a thing over time"

#

it's a discrete mathematical function that produces exactly one value at the time you run it

hybrid tapir
# sour fulcrum Probably not no

at the very least let me use 2 ints. i keep hitting roadblocks in logic just because i can only use one single basic type parameter. this is going to make my code unreadable if i take any breaks from this before im done. all that money they got and they cant even give unity events some love -_-

slender nymph
#

i mean, that's really only a limitation for passing specific values via the inspector. you absolutely can use unity events with multiple parameters if you are passing the data dynamically (i.e. in code)

hybrid tapir
#

if there was at the VERY least a way to use an editor script to make your own support for two basic type parameters id be happy. now i might have to make a 4th scriptable object script

slender nymph
hybrid tapir
#

i made a spawn function that uses 3 enums and an int value and a float value.

slender nymph
#

okay, and do those things need to be assigned to the listener via the inspector or can it be passed directly to the event?

#

because for the latter you don't need any special workarounds

hybrid tapir
#

im using scriptable objects to be workaround cuz unity events absolutely wont serialize that

slender nymph
#

you should show what you actually have, because from the sound of it you don't really need this workaround. unless you have multiple subscribers to the events that each need different data passed to them for whatever reason

hybrid tapir
#

this is the one im trying to call from the timelines unity event. the 24 is an index for the list of 160 scriptableobjects i used to hold the 3 enum values with all combinations.

#

the grid is something i have spawned at runtime using the blue squares you see in my first ss

#

i think ill restart everything from scratch except for the scriptableObjects now that i know more of the limitations i have to deal with because unityevents has to have complicated workarounds.

slender nymph
#

because the timeline signal can only be a UnityEvent and not one of the generic versions that can pass more data you are limited to the same values that a UnityEvent can pass. this is not something that would be easily changed without a lot of complex logic that allows you to specify which generic UnityEvent type you would like to use. so you are restricted to using those workarounds, but the link i sent before gives a good way to work around that limitation

#

however, if you already have the data set up in a scriptable object then really what you're doing now is probably going to be easiest

hybrid tapir
#

want me to send all of my script files here?

#

ok

slender nymph
#

literally what would that accomplish? i already told you that you need to use a workaround and why. you've found a workaround that seems to work for your workflow, but if you don't want to use that moving forward i gave you a perfectly valid option that works just fine. but no matter what you will need more code for each different type of event you want to support, that's not really something you can avoid for it

hybrid tapir
#

alright. can unityevents have scriptableobjects as parameters?

slender nymph
hybrid tapir
#

since i cant even use gameobject i will just keep the int for presetIndex and im making another scriptableobject and using Gameobject.Find in SpawnNote to do a very long workaround

slender nymph
#

why can you not use GameObject?

ashen trail
#

why would I be getting an error on other? is it the unity system im using?

naive pawn
ashen trail
#

oh, thats my mistake but its not that

naive pawn
#

the error should be telling you that you can't do = on other.gameObject

ashen trail
#

it says "other does not exist in the current context"

am I missing an import?

slender nymph
#

what is ⁨other

ashen trail
#

I'm trying to refer to the other object in a collision

slender nymph
#

what is the actual name of the parameter there?

ashen trail
#

what parameter?

slender nymph
#

the method parameter that you are trying to use

ashen trail
#

like collision?

slender nymph
#

yes

ashen trail
#

just to be clear ur talking about the Collosion2D passed through the method?
cus its just called collision

slender nymph
#

yes, notice how it isn't called "other"

ashen trail
#

OHHHH

#

sorry i thought 'other' was an actual thing within unity, im braindead

ashen trail
#

right now I'm trying to get a teleportation system working between two points, and it does work however only when the player is moving on an object and pressing a button, I want it to work when I player is just on a pad and pressing a button, how could I fix this?

slender nymph
#

you shouldn't be using GetKeyDown inside of OnTriggerStay because that runs only on FixedUpdate frames, however GetKeyDown only returns true for the very first frame that a key is pressed which is unlikely to be a FixedUpdate frame. either check the current state of the input, or flip a bool inside of OnTriggerEnter/Exit and check for the input (and the relevant bool) in Update

#

also you should ideally serialize the reference to the desired target object rather than using FindWithTag

ashen trail
#

thanks it all works better now

also I checked this with a counter but it seems stayed only gets called when u are moving in the object, I thought it would be called if u were just standing in the object

slender nymph
#

provided the relevant rigidbody does not go to sleep it should continue being called

ashen trail
#

oh, ima try to fix it but basically when I move inside the object my counter goes up but when I'm just standing in the object it doesn't go up

midnight plover
midnight tree
#

Can you describe specifically what do you need?

hoary nova
#

ok guys I am almost done with the beta of my game and all I need to do is make it so that audio can get saved when you close and open the game again. I am so done, I have been working on this SINCE YESTERDAY, and for some reason FOV and sensitivity work absolutely fine BUT NOT THE AUDIO

hell I used chatGPT and tried to get it to help me but all it gave me is my code that I did myself but cleaner

this code is like 210 lines long, can I just paste it here for help?

midnight plover
radiant voidBOT
hoary nova
naive pawn
#

read the bot message for instructions to post code properly please

#

specifically the section on large code blocks

#

what do you mean by saving audio anyways? do you mean volume settings?

hoary nova
hoary nova
# naive pawn what do you mean by saving audio anyways? do you mean volume settings?

yep, volume settings, the variables and playerprefs work fine but the audio mixer doesn't set the volume after starting the game while the sliders are set, for example if I set the music volume to zero, then stop and start playmode, the slider is set to zero while the music still plays, but the music does get set when I change the slider once again

sour adder
#

Set the volume to 1.0 at scene start? You need to think about where you change the volume, and where not...

hoary nova
#

wait lemme change it

#

well that didn't work

#

the sliders work fine but when I disable and enable playmode, the sliders are still set to what they were set before disabing playmode, but the audio just sets itself to max again, I am so confused and annoyed AHHHHHHHH

naive pawn
#

could you share your code properly

hoary nova
midnight plover
hoary nova
#

I cant, each time I try to paste the code it becomes a text file lol

midnight plover
#

You did not read a single line of the bot message, right?

hoary nova
#

I did

midnight plover
#

So where did you paste your code?

hoary nova
midnight plover
#

yeh, not read a single line of the message

naive pawn
hoary nova
#

to surrong the code with ```

naive pawn
naive pawn
hoary nova
#

oh shit I though it was websites that tell you how to lol

#

I am gonna paste the code in and see

naive pawn
#

use those services to share large code blocks

hoary nova
#

this is how I feel like right now

naive pawn
#

huh, that's unfortunate. try others

hoary nova
#

second one

naive pawn
#

right you don't have to keep posting them, we all have access to the internet

hoary nova
#

ok the third one worked, now what the hell do I do?

naive pawn
#

share that link

hoary nova
#

there you go, my dumbass finally figured it out

naive pawn
#

there we go

hoary nova
#

can you help me figure out the problem now?

midnight plover
#
master = PlayerPrefs.GetFloat("Master vol", 1f);
music  = PlayerPrefs.GetFloat("Music vol", 1f);
sound  = PlayerPrefs.GetFloat("SFX vol", 1f);

vs

mixer.SetFloat("Master", LinearToDb(master));
mixer.SetFloat("Music",  LinearToDb(music));
mixer.SetFloat("sfx",    LinearToDb(sound));
naive pawn
#

as a sanity check, have you tried debugging to make sure ApplyAudio is being called? beyond that, debug the values you're getting from playerprefs and the values before & after LinearToDb to make sure they're what you expect

midnight plover
#

Id stick with the same naming. But thats just an improvement/nice to have

hoary nova
naive pawn
#

do the other things too

hoary nova
#

yup, they work as expected for mister audio mixer : from -40 to 0, at least I think that is normal, right?

midnight plover
hoary nova
#

ok imma do it very quick

naive pawn
#

perhaps check if anything else is changing the mixer volumes

hoary nova
#

also I checked, save and load settings work properly

midnight plover
#

I would rewrite the LinearToDb, so first calculate the log10 without clamping and then clamp the result to 0.0001f and 1f Did not think obviously 😄

hoary nova
#

HOLD ON I CHECKED I THINK I FOUND THE PROBLEM

#

playerprefs have been deleted in a previous test I did, wait lemme make new ones

midnight plover
#

Could be, that you run into imprecision float values which result in something lower than 0.0001 which results in miscalc and reset to 1

#

Playerprefs should create newones with SetFloat/GetFloat(defaultValue)

hoary nova
#

okay okay, playerprefs work fine actually

#

lemme try something

#

didn't work either

midnight plover
#

Did you try to rewrite the Log10 method?

hoary nova
#

yup

quartz ridge
hoary nova
#

do I remove the * 20?

hoary nova
#

I am the most delusional person out here and I won't stop until I figure it out

#

ok I am gonna remove the * 20 and see if it works

naive pawn
#

i'm using a similar method in my own impl

audioGroup.audioMixer.SetFloat($"{audioGroup.name}Volume", Mathf.Log10(Mathf.Max(value, 0.0001f)) * 20);

hoary nova
naive pawn
#

the rest probably isn't going to be relevant to your case, i don't have saving

#

i mean, not like there's much there to begin with

#

@hoary nova have you verified that the LinearToDb(master) is the value you expect right before you pass it to mixer.SetFloat?

hoary nova
#

lemme try and see

#

yeah it works fine, it goes from 0 to -40

naive pawn
#

shouldn't that be -80 to 0

#

log10(0.0001) should be -4

#

anyways, are you getting any warnings or errors?

naive pawn
#

are SetMasterVolume etc perhaps getting called

hoary nova
#

it is, yes

#

they are called through sliders

#

I am gonna try and see if calling them at the start works

naive pawn
#

i mean at the start, the code you have assumes it doesn't

lunar axle
#

so i have a monobehaviour class ⁨⁨⁨A⁩⁩⁩ that depends on ⁨⁨⁨Rigidbody⁩⁩⁩:

⁨⁨⁨```c#
[RequireComponent(typeof(Rigidbody))]
public class A : Monobehavior {
// ....
}


inside another script, i run:

⁨⁨⁨```c#

gameObject.AddComponent<A>();
```⁩⁩⁩

in runtime. the thing is will the ⁨⁨⁨`Rigidbody`⁩⁩⁩ component automatically added when class ⁨⁨⁨`A`⁩⁩⁩ is added?
naive pawn
#

or, yknow

hoary nova
#

GUYS I GOT IT TO WORK YEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAH

#

ALL I HAD TO DO WAS PUT ApplyAudio(); ON THE START FUNCTION

unique pagoda
#

GUYS I don't know how to code😭💔

#

I've only ever coded scratch

#

and I still barely know💔

naive pawn
#

anyways to learn c# or unity, see the tutorials pinned in this channel or unity learn

#

!learnm

radiant voidBOT
naive pawn
#

!learn

radiant voidBOT
echo ruin
#

I have an array called ⁨⁨target[]⁩⁩ and I want to use ⁨⁨target⁩⁩ as a parameter in the same class. Using ⁨⁨this.⁩⁩ got rid of the error, but just to make sure, does ⁨⁨this.⁩⁩ pick the class array or the parameter in the function?

#

⁨```c#
public bool IsTargetValid(int host, int target)
{
if (enumsData[target].State == State.Dead)
{
enumsData[host].State = State.Idle;
this.target[host] = host;
return false;
}
return true;
}

keen dew
#

Surely if it picked the parameter you'd still get the same error for trying to use an int like an array

naive pawn
#

x.y gets the y that belongs to x, or in the context of x

echo ruin
#

If I remove ⁨[host]⁩ it gives an error

echo ruin
naive pawn
#

functions aren't first class members in c#, so it can't be the function

echo ruin
#

That's all I needed to know

naive pawn
#

thonk i guess that's kinda a blurry line, since you can use functions as their equivalent delegate

#

i remember having this discussion in the ts server and it did not yield any concrete answers lmao

polar acorn
#

But this always refers to the Object running that line of code

naive pawn
#

this just points to the current instance, as a rule - not just in c#

#

not much use to have it point to the current function call

#

i guess that's another angle - the function call doesn't exist in this way, and target is within the context of the function call, not part of the function, so this.target can't possibly be the param

mint imp
#

Hey guys im instantiating an object at a random point on a sphere.
I already have that handled
but now im trying to set its rotation so that "up" is the same direction as
[Quaternion upFrom Planet = centerOfPlanet - positionOfSpawnedObject]
so that it faces "up" no matter where it spawned on the planet.
INSTANTIATE(positionOfSpawnedObject, upFromPlanet)

but its not actually working?

#

it works near the equator but not the poles

#

so theres something im not understanding

naive pawn
#

what code are you actually using

#

please don't retype code, you lose a lot of information doing that

#

Quaternion x = a - b with Vector3s isn't valid

ivory bobcat
mint imp
upper token
#

How can I make the Cinemachine's movement smooth when following an object?

wintry quarry
#

if it is not smooth, you have misconfigured something

#

The most common issue is the use of Rigidbody without interpolation or with some code that breaks interpolation

upper token
wintry quarry
naive pawn
#

also consider if your object might be the one jittering, rather than the camera

wintry quarry
#

you have interpolation enabled here but your code may be breaking it

#

Any code that directly modifies the position or rotation of the Transform will break interpolation

queen adder
#

Good day to everyone. Just a quick question about the Pong game. Which script would make sense call the ball reset whenever the ball triggers the zone and the score goes up? Should the ball call on trigger enter on itself or the score zone calls when the ball enters its trigger? I would guess the ball only knows where to reset its position, direction and velocity, and the score zone triggers the "event" that a ball has triggered its zone and then the ball reset will be called from the score zone script

swift crag
#

I don't think there's a clear answer in this case

wintry quarry
swift crag
#

I guess I'd lean towards the score-zone being responsible for telling the ball to reset

wintry quarry
#

One might imagine more than just the ball needs to reset. In which case you could either:

  • reload the whole scene
  • Have some centralized manager that imperatively resets every object that needs resetting
  • Have some event that fires that any "resettable" object listens to and resets itself when the event is fired.
swift crag
#

in that case, either source (the ball or the zone) would just tell a game controller that it's time to reset

#

and the controller would handle the rest

#

you'd tell the controller "this ball just entered this zone!"

#

maybe you're doing multi-ball, so the game doens't reset until every ball hits a zone

queen adder
frail hawk
#

and unity provides the UnityEvent, which comes handy for you

queen adder
frail hawk
#

yeah you can do it as you want, just saying

polar acorn
stray wigeon
#

Not sure where to ask but I'm really trying to add text to a dark scene which will later get illuminated by lights. SRP/Unlit or Tmp/DistanceField(Surface) don't work. Ive been scouring niche Unity Forums for the past hour.

frail hawk
#

you mean ui text right

hexed terrace
#

not in a code channel 😄
if you can't find an appropriate channel topic, then #💻┃unity-talk is the place

stray wigeon
#

I mean... I made it through UI- TMP, It is on scene. Im trying to make a diegetic interface.

still herald
#

anyone here started and finished the program of programer jr in unity learn? it's worth it do it? i'm new in C# btw

frail hawk
#

everything is worth it if you learn somethign new.

#

pretty sure the course will teach you some

still herald
#

okay, thank you!

queen adder
#

First watch and then do

still herald
vital otter
#

if I have a lerp function where a = Mathf.Lerp(a, b, Time.deltaTime), will that desync gradually on different framerates?

swift crag
#

an intuitive explanation:

#

at 1 FPS, you're doing Mathf.Lerp(a, b, 1)

#

so you obviously just get b

#

At 2 FPS, you're doing Mathf.Lerp(a, b, 0.5) twice

#

you get 75% of the way to b

#

That article includes a function that gives you very similar behavior, but does it in a framerate-independent way

vital otter
#

ok thanks!
that makes what I want to do about 10x more convoluted

swift crag
#

It's very useful! I use it for smooth-damping motion in VRChat (using constraints + an animator to calculate the weights)

#

You can just swap the ExponentialDecay function in

#

You may also want Mathf.SmoothDamp or Mathf.MoveTowards

#

for springy and linear motion, respectively

swift crag
#

now you can write ExponentialDecay(...)

#

(or just do MathTools.ExponentialDecay(...))

vital otter
#

im trying to make a system where an entity slowly pans the player camera towards it with a strength correlating to the distance the entity is from the player

feral jacinth
#

yo is there a wiki for unity?

#

somthing like the roblox documentation for roblox studios

swift crag
#

there isn't a large community-run wiki, as far as I know

#

(e.g. like that Unreal one)

chrome tide
#

there are unity docs tho

swift crag
#

yeah, that's the first point of reference

grand snow
#

There used to be a unity wiki but that went years ago

#

Unitys official docs are soo good that they cover everything you need

swift crag
#

yeah, they're quite good

#

one really important thing: package documentation doesn't live in the manual!

#

e.g. Unity UI was broken out into a package ages ago

#

but many google results still point you to the very old manual pages

feral jacinth
#

thank you

grizzled forge
#

hi all. i'm still new to unity, and teaching myself c#, but i'm trying to make a metroidvania (hollow knight style) and i was just wondering if anyone could check out my character controller to give me any tips? or just let me know if i'm coding like an idiot, lol

#

!code

radiant voidBOT
grizzled forge
#

i believe i posted that right

wintry quarry
#

or wait actually - this is for gravity in Update? This belongs in FixedUpdate

#

and it makes sense with fixedDeltaTime in there

#

For rb.linearVelocity.y; - Rigidbody2D lets you just do rb.linearVelocityY;

grizzled forge
#

the reason i put it in update is because of how "WasPressedThisFrame" works on input, and would miss inputs while in fixed update. it's the only way i knew how to fix that thought :(

wintry quarry
#

input handling goes in Update.
Physics in FixedUpdate

#

The way to do this with a jump is by storing the user's intent to jump in a variable, and consuming it in FixedUpdate

grizzled forge
#

oohhh!

wintry quarry
#

e.g.

bool userWantsToJump;

void Update() {
  if (IsGrounded() && JumpButtonPressedThisFrame()) {
    userWantsToJump = true;
  }
}

void FixedUpdate() {
  if (userWantsToJump && IsGrounded()) {
    Jump();
  }

  userWantsToJump = false;
}```
grizzled forge
#

gotcha gotcha! that makes a lot of sense actually. i knew moving to update for physics was bad, but i for some reason didnt think of doing it separately

#

thank you for the help! i'm very much still learning it, so any tips are appreciated!

lucid mauve
#

!code

radiant voidBOT
distant escarp
#

Howdy, I'm back! I've got my gerstner waves shader running and a functional recreation of the shader on my CPU that allows my character to walk on the gerstner waves. However, I'm having trouble syncing my shader (wave visual) with my code (wave physics); would anybody be able to help me?

rich adder
distant escarp
rich adder
#

should probably share code and anything relevant then

distant escarp
#

oh yeah lol one sec

frosty hound
#

Showing your code is onlyhalf the issue though. It could be fine, but it could just not be identical to how your shader is handling it.

distant escarp
mint imp
#

Hey guys so i have objects randomly spawning on the surface of my planet.
Now I'm trying to spawn these object that their "up" rotation is "up" away from the planet
I already have the direction from the center of the planet to the position that the object is spawning... I just dont know how to rotate the object in a way where that direction is "up"

wintry quarry
#

Vector3.up is arbitrary

#

there are infinite possible valid look directions so you'll need to pick one somehow

#

you could just pick a random rotation around that up axis if you want

#

for example:

Vector3 localUp = positionOfSpawnedObject - targetPlanet.position;

float randomAngle = UnityEngine.Random.Range(0f, 360f);
Vector3 randomDirection = Quaternion.AngleAxis(randomAngle, localUp) * Vector3.forward;
Quaternion rotation = Quaternion.LookRotation(randomDirection, localUp);```
#

Something like this should work I think?

#

basically imagine a person standing on a planet. They can rotate freely in any direction while their head still points up.

#

You need a way to decide which way they are looking

sour fulcrum
#

If I’m understanding right Generally this kind of thing would be done by raycasting at the planet (which you might be doing already) and using the RaycastHit’s .normal value which basically will be a direct away from the surface you hit

sour fulcrum
#

Praetor’s advice might be more valid

wintry quarry
sour fulcrum
#

Right yup

#

misread and didn’t realise they already had the info just not how to use it 👍

#

Food poison brain

static bobcat
#

so i just started coding like a hour ago and im trying to make flappy bird with a yt video ofc. but i restarted my pc and suddenly for some reason when i go and make a custom script it goes into visual studios. its just blank there's no code what so ever?

wintry quarry
#

If you did "new monobehaviour script" from in Unity there should be a basic template

mint imp
static bobcat
#

im also unable to type in it so i dont think its that

wintry quarry
#

unable to type sounds like your project hasn't opened up properly in VS

#

Most likely you haven't configured it for Unity properly

static bobcat
wintry quarry
radiant voidBOT
static bobcat
#

i tried stuff that it said but its still blank

mint imp
wintry quarry
#

also if the planet is a sphere, the raycast seems redundant

#

To get a position on the sphere you could just do:

Vector3 spawnPos = planetPosition + Random.onUnitSphere.normalized * (planetRadius + elevationAboveSurface);```
sick storm
#

can anyone help me with the pixel perfect camera, i want to increase what the player can be see while keeping pixel perfect. My problem is my player view is either too small or too large

mint imp
# wintry quarry also if the planet is a sphere, the raycast seems redundant

The planet isnt a perfect sphere so i wasnt sure that would work and i wanted to make room for modeling it more later
Probably sounds silly but im finding the "Random.OnUnitSphere" intentionally above the surface, then shooting a raycast back down from that point to find the elevation of any given point to make that the spawn location.

wintry quarry
mint imp
wintry quarry
sick storm
wintry quarry
sick storm
sour fulcrum
wintry quarry
# mint imp It is yes

Can you try this instead?

Quaternion alignment = Quaternion.FromToRotation(Vector3.up, localUp);
Quaternion randomSpin = Quaternion.Euler(0f, Random.Range(0f, 360f), 0f);
Quaternion rotation = alignment * randomSpin;```
mint imp
static bobcat
#

danm this sucks is there like a 90% working way to fix this? i have tried alot.

static bobcat
# teal viper Fix what?

I’m using unity and I’m trying to code and it worked fine but I restarted my pc and now when I double click a script it sends me here to just blank

teal viper
cobalt dagger
#

Is there a way to constantly add force without it being in Update or FixedUpdate?

sour fulcrum
#

Why?

cobalt dagger
#

I am trying to make a dash and it checks every frame if the player is dashing which id rather have it do the dash when the player activates it and it runs a function that does it without having to check every frame if the player is dashing

sour fulcrum
#

I think you can use a coroutine with a while + WaitForFixedUpdate()

naive pawn
#

after a WaitForFixedUpdate() the coroutine will be in the fixed timestep, yeah

#

or if it doesn't need to be on the fixed time step, a typical coroutine would also work

sour fulcrum
#

phone pseudo but i think

while (true)

yield return new WaitForFixedUpdate()
//applyforce

and then kill the routine when needed, or handle it in the while condition directly

cobalt dagger
#

Thanks ill try it out

#

Idk if this is a dumb question, but how bad is just 1 bool if statement inside of Update or FixedUpdate for performance?

sour fulcrum
#

That kinda shit just does not matter

#

crumbs on the floor

naive pawn
cobalt dagger
#

Oh so it basically doesn't matter, okay thanks

wintry quarry
naive pawn
#

5000 is a bit small

wintry quarry
#

You know the answer then

static bobcat
#

what would be a common mistake when trying to put text onto the ui?

#

cause i cant see it when i play the game

keen dew
#

You'll solve the problem much faster if you ask about it directly instead of some generic common cases

#

Post a screenshot of the editor to #📲┃ui-ux with the scene open and the text selected

static bobcat
#

why doesnt this work? its not letting me put the TMP text into the scoretext

sour fulcrum
#

things are only type, not two

#

Commas are also never used like that

#

You’d want just

public TMP_Text scoreText;

there

#

But actually TextMeshProUGUI is the type your probably looking for

naive pawn
#

configure your ide

#

!ide

radiant voidBOT
naive pawn
#

it's a superclass for both the gui and worldspace versions

sour fulcrum
#

oh I thought they were different

#

Til

#

Scary

young sapphire
#

Is unity good for making games?

static bobcat
naive pawn
#

clearly not, it should be showing errors

#

object isn't a valid identifier

young sapphire
naive pawn
young sapphire
#

Does unity offer free courses

#

I want to learn the programming part of unity its what im more interested in

#

Where can i find this tutorial

naive pawn
#

yes

#

!learn

radiant voidBOT
naive pawn
#

there are several online as well, and pinned in this channel

young sapphire
#

Ok thx

static bobcat
#

i did it i had to put using TMPro;

naive pawn
#

you should configure your ide so it can do that for you

desert yarrow
#

so can i have your help on something. i was given this task in class. i have this box "player". which is supposed to move forword when the game starts and move left and right with arrow key. i have done until this point. later i was told to add a sound for the game i did that too. but in this next part the player was supposed to collide the enemy box and the game over. but the player box collides but the code for the crash ant working. i assigned the enemy tag to the another box but it didn't work out and when the game overs the game over ui is supposed to come but the i dont where to put the code for the canvas. and the crash sound.

keen dew
desert yarrow
#

i didnt understand

#

how should i fix it

keen dew
#

You have to set the audio source you want to play

desert yarrow
keen dew
#

It's an audio source, not a sound

desert yarrow
desert yarrow
#

so what should i do?

naive pawn
#

create an audio source and assign it

#

well you already have one actually

keen dew
#

Which audio source do you want it to play?

naive pawn
#

so, just assign it

#

or get it via GetComponent

desert yarrow
#

but what i concerned about is the collision.the player box is passing thorough the enemy box how do i fix that first?

keen dew
#

You don't need to fix that, when playing the audio doesn't throw an error anymore it'll load the next scene

#

Although your next issue will be that the sound won't have time to play because it goes to the next scene immediately

naive pawn
#

does your player have a rigidbody? if so, you should be moving via the rigidbody, not the transform

#

!ask

radiant voidBOT
# naive pawn !ask

:thinking: Asking Questions

:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.

-# For more posting guidelines, go to #🌱┃start-here

desert yarrow
naive pawn
#

you should be moving via the rigidbody, not the transform

desert yarrow
keen dew
#

wtf

unkempt holly
#

I want help with slider

#

The slider is only moved with the arrows and not the mouse.

naive pawn
#

there's quite a few ways, try googling around

naive pawn
unkempt holly
#

i can click on slider but i can move it only by arrows

midnight plover
unkempt holly
#

default

midnight plover
# unkempt holly default

can you click anywhere on the slider and will it move the indicator there? or how do you know, you can "click" it with your mouse?

unkempt holly
#

color change

#

the handle is white but if i click on handle the color is change to gray

#

i can use arrows but i cant use mouse

#

arrows or WSAD

midnight plover
unkempt holly
#

i try add new slider and it works

midnight plover
# unkempt holly i try add new slider and it works

So find the difference between your current one and the default one. Could be something on settings or you disabled some raycast on an image while trying to customize it and what not. not a code issue

unkempt holly
#

okay i try it thank you

faint osprey
#

Does anyone know how many times per second the ‘onaudiofilterread’ function is called

#

It says on the docs around every 20ms but it seems way faster than update so that cant be right

naive pawn
#

or do you mean, in your testing, onaudiofilterread is being called much more often?

faint osprey
#

On audio filter read runs on a different loop to update and is called dependant on the sample rate and buffer size

#

However not sure how to calculate it

midnight plover
faint osprey
#

Yeah i think its buffer size / sample rate

midnight plover
#

So 48khz would be 48000 a second, devided by the buffer you want to use, essentially slicing the sample rate into parts. there you get your callback rate

naive pawn
#

you get a value in Hz there, if you want a value in s or ms then it would be buffer/sample rate, no?

midnight plover
#

Hz is basically cycles per second, so second divided by the cyclecount would give you the ms, from what I understand there

naive pawn
midnight plover
bright oxide
#

Hello, I use a CapsuleCollider2D with a RigidBody for my sidescroller game. How do I prevent the player from gliding off when standing near platform edges?

naive pawn
#

could consider a boxcollider instead, depends on the level geometry you need to handle

bright oxide
#

Are there ways of pulling it off with a capsule collider?

#

Like sticking to ground or something

tender mirage
#

Are you planning on adding slopes?

bright oxide
#

Because my teammates tell me "its the first thing they teach you in game programming class"

#

we don't have slopes so I don't really see a point in using capsule colliders personally

frosty hound
#

The point is that it won't get stuck between seams in your colliders.

#

Box colliders can, resulting in the occassional "hop" when moving along a surface if there is a seam.

bright oxide
#

ah, well in that case what is the way to solve it?

grizzled steppe
#

I found a work around for small textures!

#

Apparently theres a setting called Non Power of 2 that can mess with the color indexing

hexed terrace
#

this is a code channel

grizzled steppe
#

I'm making an outfit change script

frosty hound
#

Unfortunately, the proper way to solve it is to not rely on a collider to do all the ground collision logic for you. Polished/advanced character controllers use raycasts in addition to the collider to handle the movement. For the case of sliding off the edge, you could detect that the outter edge of the collider was hanging off the side and if far enough, either prevent additional movement (if you don't want them to fall off), or force the fall.

solar star
#

hi guys. is this the right place to ask questions? :3

#

i've got a weird issue

#

i'm having a problem with registering overlaps/triggers.
on the left is a character controller (with grey capsule mesh). on the right is a green boxcollider.
in the left image, i do NOT get an overlap event, even though the box and the capsule are clearly overlapping.
in the right image, i DO get an overlap. the only difference is that I moved the boxcollider closer to the capsule.

why do I not get an overlap in the first case?

rancid tinsel
#

what on earth is Visual Studio on? or am I dumb?

polar acorn
gaunt cave
#

sup

rancid tinsel
naive pawn
#

try the show potential fixes and see if there's something to generate method stubs

#

then see how the method stubs are written

rancid tinsel
#

its with lowercase e, but why???

polar acorn
rancid tinsel
polar acorn
rancid tinsel
#

I have

#

let me restart VS ig

#

very confused

#

maybe I've got too much stuff in one file rn and it's being weird

hexed terrace
#

delete the two methods you created, and get VS to auto create them for you

naive pawn
#

do you have multiple interfaces with that name, perhaps

naive pawn
#

read the rest of your errors

rancid tinsel
#

OH

#

yeah I do 🤣

rancid tinsel
#

thanks guys!

urban saddle
#

Hi I have a question with regards to creating an inventory system in Unity. I've been working on an inventory system for a demo game. I have it partially working. My inventory system architecture plan is as follows:

  1. I create the inventory and store it in memory but not the game objects. I use a wrapper for this.
  2. Inventory Slots are stored in the inventory class as a 2D array so one can set the rows/columns dynamically.
  3. The inventory slots themselves contain an inventory item class which is a wrapper for a particular item that may go in that slot. It contains a field to store the actual item
  4. When the player needs the inventory for instance by hitting a certain key, I then spawn in all the game objects in the world.
  5. When the player is done with the inventory all the game objects get destroyed.

My question is, is this the correct way to do things? I'd imagine having game objects for every inventory in the scene wouldn't be too performance friendly, hence why i generate them on demand. I have seen a lot of Youtube video tutorials where they either manually create the inventory with each slot in Unity or they generate them but leave them in the scene but neither seems ideal

naive pawn
#
  • there's not going to be 1 specific "correct" way to do such a thing, if it works it works
  • keep in mind that there's also a cost to instantiate all those gameobjects. you have to consider the tradeoff between time and space (aka speed vs memory)
urban saddle
#

that is a good point

naive pawn
#

I'd imagine having game objects for every inventory in the scene wouldn't be too performance friendly
what aspect are you concerned about exactly? deactivated gameobjects don't get updated, for example, and the memory footprint is there, but it would probably be much less than you think. do you expect to have, say, a million inventory slots total loaded at once?

urban saddle
#

well say im making an rpg game, and u go to town and theres a bunch of npcs selling stuff

#

there might be 20 npcs with 1 or more inventories each

naive pawn
#

and how many slots would they have

urban saddle
#

i guess my question how much memory would a gameobject take up vs keeping the same kind of information in memory as part of an array minus the gameobject and all its components like image etc

#

well could be 30 or so slots

#

or more

midnight plover
#

One question for you, are you using addresables or are they assigned somewhere in the inspector within the scene?

urban saddle
#

im not using addressables

midnight plover
#

Than its in memory anyways, unless you load it through resources with a string

#

Everything you assign in inspector is basically "preloaded", as long as its not addressable/assetreference. Anyone correct me if I am wrong.

naive pawn
# urban saddle well could be 30 or so slots

let's take a pessimistic estimate then - 40 npc with 50 slots each would be 2000 inventory slots
just the gameobject on its own, plus maybe a component referencing an so, would be, from a vague estimate, 90 bytes, so let's go with 300 bytes
so the dormat inventory slots would be 600000 bytes, aka 600 kb / 0.6 mb
that's like, 2 small pngs worth of memory

#

even with these extremely pessimistic estimates, the memory footprint is still practically nothing in the scope of a game

urban saddle
#

each inventory item has an image for an icon too which make that a bit bigger

naive pawn
#

it'd just be a reference, the inventory slot doesn't hold the entire image

urban saddle
#

also related to this it worth using an 'inventory manager' like a singleton kind of setup on a game object that knows about all the inventories in the scene

naive pawn
#

and it wouldn't be loaded and drawn when it's not open

urban saddle
#

ok

naive pawn
solar star
#

im kinda going mad here.
is there a threshold at which two colliders overlap? because the green box triggers an "OnTriggerEnter" event but the white one doesnt.
the boxes are exactly the same object in every other regard. it's just the green one is a little closer. but BOTH are overlapping visually, and both should trigger OnTriggerEnter?!

urban saddle
#

i ask cause so many youtube tutorials seem to use one

#

to me it doesnt make sense either, the inventory should be part of the object its related to

naive pawn
naive pawn
solar star
#

no filter, and both boxes are the same prefab

#

just different spawnposition

naive pawn
#

could you show the code you're using to check for the trigger message, just as a sanity check

#

(i don't think it'd be there, but it'd be nice to rule that out)

solar star
#

its just this. its called in the object with the boxcollider

#

box is an object with BoxCollider component set to IsTrigger: true and a script

#

the capsule is a CharacterController

naive pawn
#

you might want to add a context argument to that log to see more clearly which box got triggered

solar star
#

the hitbox thats closer to the capsule gets triggered.

#

so weird man

#

this is the code to spawn em

#

(i know im reassigning the variable but i dont do anything with it anyway for now, so i think that doesnt matter)

naive pawn
#

wait are you just expecting the boxes to hit the capsule

solar star
#

im expecting them to trigger an overlap

#

both

#

not just the closer one

naive pawn
#

i thought the issue was the boxes hitting each other but only sending a message to one...

solar star
#

since both of them are visually overlapping, im expecting both of them to send an OnTriggerEnter message

silk night
#

Is atleast one of your involved objects a rigidbody?

solar star
#

no, but I also tried with that and that didnt work either. I will try again just in case.
and if that was an issue, wouldnt both stop firing? its weird. lemme check tho

silk night
#

Oh yeah then both would stop firing, sorry I gotta read through your whole conversation here

#

it's just the green one is a little closer
does the white one also trigger if you put it closer?

Which object did you attach the OnTriggerEnter script to?

solar star
#

maybe I shouldnt use a CharacterController component and try a standard rigidbody and rewrite my little movement code :[

solar star
silk night
#

My guess: they trigger each other, player does not trigger at all

solar star
#

does the white one also trigger if you put it closer?
yes

silk night
#

maybe I shouldnt use a CharacterController component and try a standard rigidbody
You can attach a kinematic rigidbody to something controlled by a charactercontroller

solar star
silk night
#

do an explicit PlayerCharacter == null check

naive pawn
silk night
#

huh i thought boolean conversion and object?.property are problematic when working with unity objects

naive pawn
silk night
#

Ah good, ive been avoiding boolean conversion in the past, good to know I can use it

solar star
#

i'll just try the same setup in a new project on unity6.3. im on 6.2 right now

#

thanks for taking the time tho ❤️

#

different but kinda related question: is there a way to visualize the overlapbox created by Physics.OverlapBox()?

#

i promise i wont spam more after that

#

😄