#💻┃code-beginner

1 messages · Page 662 of 1

tepid summit
#

oh

north kiln
#

Just Alt-Enter (show potential fixes) in your screenshot, and import the appropriate namespace

tepid summit
#

i didnt have using system.collections

tepid summit
#

wierd

#

thought that was adefault

#

mightve accidentally deleted it

#

anyways have a good night

hexed terrace
tepid summit
#

is that a hub update

#

becuase im still on a 2022 vers of editor

winter plover
#

hello

#

anyone mind trying to help me with a specific script

#

the idea is

#

that theres a distance between a empty gameobject and the player as a float

#

and if the player is in that distance and they click f, one object is set active and the other one is set inactive

#

but when i go close it doesnt do anything

#

i can give the script too

hexed terrace
tepid summit
#

theyll get to you

hexed terrace
tepid summit
#

also probably dont offer to share the script and just share it

hexed terrace
#

!ask

eternal falconBOT
winter plover
#

i lit went into a channel

#

and i just said

#

that i already did all this

keen cargo
#

did you read the whole thing

winter plover
#

digga

#

i said i already

tepid summit
winter plover
#

did all the steps in ask

#

or wtv

winter plover
keen cargo
#

all of them? are you sure?

winter plover
#

yes no results

#

i even tried chatgpt

#

nd it didnt help

keen cargo
#

read the last line

tepid summit
#

i could probably find some results real wuick

winter plover
#

so can i send

#

my script

#

or am i gonna get muted for 30 days

frosty hound
#

Whine less

keen cargo
#

why would you get muted for sending your script, just send it

frosty hound
#

!code

eternal falconBOT
winter plover
#

before to me

#

cuz i "flooded"

frosty hound
#

Which you are still doing.

winter plover
#
using UnityEngine;

public class Door : MonoBehaviour
{

    public GameObject maindoor;

    public GameObject closeddoor;
    public GameObject opendoor;

    public GameObject player;

    private bool IsOpen = false;



    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        opendoor.SetActive(false);
        closeddoor.SetActive(true);
    }

    // Update is called once per frame
    void Update()
    {
        float dist = Vector3.Distance(player.transform.position, maindoor.transform.position);
        float radius = 5f;


        if (dist <= radius && Input.GetKeyDown(KeyCode.F))
        {
            if (!IsOpen)
            {
                Debug.Log("F pressed in radius of the door");
                opendoor.SetActive(true);
                closeddoor.SetActive(false);
                IsOpen = true;
            }
            else
            {
                opendoor.SetActive(false);
                closeddoor.SetActive(true);
                IsOpen = false;

            }
        }
    }
}

hexed terrace
#

probably told how to share, then ignored and did it wrong

tepid summit
#

use hastebin

keen cargo
#

this works too, it's pretty small

winter plover
hexed terrace
#

If they're too big, you should be using a paste site.

winter plover
#

ye i use pastebin

hexed terrace
#

You need to add logs into your if statements and see what's going on.

Nothing immediately jumps out as being wrong

#

perhaps the setup in the scene is

tepid summit
winter plover
#

i checked outputs

#

and i added prints too

#

didnt rlly get anything

#

wait i have an idea im gonna add a print(dist);

#

before the if statement

hexed terrace
#

Debug.Log($"distance is: {dist}");

winter plover
#

ye ima do that before the if statement

winter plover
tepid summit
hexed terrace
#

to allow for putting vars directly into the string

tepid summit
#

ah i see

winter plover
#

very useful

#

ty

hexed terrace
#

instead of doing Debug.Log("distance is: " + dist); which isn't efficient

tepid summit
#

is it really that different

hexed terrace
#

it has a name, which escapes me atm

keen cargo
#

string interpolation? something like that

tepid summit
hexed terrace
#

one log? no.
thousands? Yes.

winter plover
#

ok so @hexed terrace i think i figured out the error

tepid summit
winter plover
#

the distance never goes under 5f (which is the one i desire)

#

look

hexed terrace
winter plover
keen cargo
#

yeah it's string interpolation, just checked

winter plover
#

the white part u see is the game object

#

and the dsitance is 17

tepid summit
#

this ss doesnt say a lot

winter plover
#

eh idk how to explain it

#

this is where my empty go is positioned

#

and when i go close to it

#

the dist is high

tepid summit
#

swap the vars

hexed terrace
#

1- actually look at the console, not the single line at the bottom (click the console tab)
2- are you sure you've got the correct game object assigned? Not that it looks like there's a lot of things there that you could do incorrectly

tepid summit
#

so instead of Vector3.Distance (player, door) do Vector3.Distance (door, player)

winter plover
winter plover
#

i think if i just

#

put the closed door object

#

or open door object

#

instead of an empty game object

keen cargo
#

please write your sentences in one message, finish your sentences

winter plover
#

mb im used to it

hexed terrace
winter plover
#

ok so

#

i changed the vector3.distance to be the closed door (actual object) instead of the empty gameobject and it works

hexed terrace
#

"Door" might be at some position far away.
While DoorOpen/ Closed were moved independently, giving them a different pos.

Having your pivot mode set to 'center' and selecting the "Door" gameobject will put the transform axis at the doors. Chaing to pivot (Z is the toggle hotkey) will show you were it really is

winter plover
#

alr

shrewd swift
#

for a single scene loaded, is there any Awake order guaranteed ? (for example from top to bottom hierarchy list)

winter plover
tepid summit
#

is it random?

shrewd swift
#

mh, i wonder what would a good approach when i have some "awake" dependencies between my objects

#

i dont really like the idea to have them query eachother and manually call some Init function

hexed terrace
#

A manager script to load things in order.

OR

Use Awake to setup the class, getting references etc
Use Start to initialise the class with that data ^

#

Doing the Awake/ Start way is good practice regardless

shrewd swift
#

the thing is this is an issue if i have Object 1, 2 and 3
and each ones needs to wait for the other to init itself before us

hexed terrace
#

before us
?

shrewd swift
#

for example
Object 1 inits in Awake
Objects 2 inits in Start (gets info from Object 1)
Object 3 needs Object 2 to init before it does anything, you cannot place it in Start because of inconsistent order

#

in this scenario the usual way is to have a bool isInited and a delegate onInitProcessed and have any dependent object use that on awake/start/whatever to know if it can run or not yet

hexed terrace
#

Either the code needs refactoring with less dependency on each other.
Or use a manager script to enable things in order.
Or Object 2 has a reference to Object 3 and calls Init() when it's done.

ebon fox
#

chill mal die wollen dir nur helfen

winter plover
#

😭

winter plover
prisma rock
#

guys Im having an annoying problem where my characters spawn with crazy speed but I need to press on the prefab to apply the normal speed values in the game scene couldnt fix it at all

burnt vapor
eternal falconBOT
prisma rock
burnt vapor
#

We don't know either

#

Share video's context, etc

prisma rock
winter plover
#

hello

#

is there a way to make a wait in the update function

#

like a delay in update

alpine fog
#

you can run a coroutine or unitask and wait there

winter plover
#

it will just

#

create new coroutines

#

if i do it in update

alpine fog
#

create one repeating coroutine then

burnt vapor
#

An update runs every frame, delaying it meaks you essentially block everything

#

You probably want to log a timestamp and simulate a delay that way by saving a variable Time.time and then check if the current Time.time exceeds this timestamp

#

Alternatively use a Coroutine combined with a boolean to indicate it runs, or some other way.
Context is important there so you should share what you actually want to do.

brave robin
winter plover
#

ive made a simple door script

#

and i want it so

#

when the player clicks f in the proximity of the door (this is all in update)

#

the text that i have turns green then white again

#

after a short wait

burnt vapor
#

Okay so timestamps in that case

#

If the player clicks, set a timestamp and update the text. If the timestamp ends, remove it again

winter plover
#

idk what those are

#

im a lil new

#

wait actually

burnt vapor
winter plover
#

cant i just do a different indicator

#

like an expanding circle

#

like when u click f it makes a text that makes a circle expand

#

maybe that

burnt vapor
winter plover
#

nah i re-decided im gonna make like a circle that expands when the player clicks f slowly

burnt vapor
#

Coroutines are easier, but messier

burnt vapor
winter plover
abstract jackal
#

Hi guys! It's been a day and I still haven't found a solution to this warning. The Gizmo isn't working in Play mode in Unity 6.1.
CommandBuffer: built-in render texture type 3 not found while executing (SetRenderTarget depth buffer)

polar dust
#

think of it like a light switch. you turn the switch on, 3 seconds go by, the switch automatically turns off

in your case, when you click the door, set a bool to true and save the current Time.time, this is like you turning the light switch on
all the while the bool is true, you keep checking if the current time is more than 3 seconds than the saved time. this is like the light being kept on.
once 3 seconds is up, set the bool to false. the light switch is turned off.

then all you need is to do one thing when the bool is true, so setting the text color to green
when the bool is false, set the text color to white

burnt vapor
#

Time.time is great

gentle bone
burnt vapor
#

Once you get to using timestamps properly you can do a ton with them. Pretty much everything is possible with them where Coroutines can be more messy

#

Also, for multiplayer it's a lot better due to their small size in most cases

abstract jackal
polar dust
#

can there be problems about using a coroutine effectively like a stopwatch?

burnt vapor
#

Whereas if you have a synched timestamp, it will properly invoke on the remaining four seconds

#

This is pretty much unavoidable unless you agree on when it should stop, not how long it should last

abstract jackal
polar dust
#

thats what ive wondered, but multiplayer isnt something ive had experience in

burnt vapor
#

I would generally advice to use it as much as possible regardless for the consistency

polar dust
#

the way they work still isnt that clear to me, they feel like they behave like youre making a thread because the way they execute doesnt exactly depend on the update loop

burnt vapor
#

Timestamps?

#

It's a single variable

polar dust
#

I mean if an update frame happens to lag, the couroutine can keep running its process even if update hasnt finished yet

calm sierra
#

does anyone have some good tutorials for fps movement? preferably covering complexer stuff like dashing and sliding too. i found one but it was a bad tutorial and used a rigidbody and i would prefer a character controller

burnt vapor
#

Vs a synchronized timestamp which is always ending at some point

#

It's not about lag DURING a Coroutine. Pretty sure that WaitForSecondsRealTime class or w/e fixes that

polar dust
#

yeah, timestamps are what id always do for a stopwatch. coroutines are how I used to do it, and I think thats purely because you specifically tell them to wait X seconds

burnt vapor
#

In most cases, anything involving a Coroutine or a timestamp relates to a visual feature. If not, it would be purely serverside anyway

#

So then you don't really worry about that

thorn holly
calm sierra
#

i watched plenty of tutorials, i get how it works but i could write one myself just yet

calm sierra
#

also, why is gravity so bad?

#

its just way too strong, doesnt matter if i do anything to it

#

also, my groundcheck just deletes itself once i hit play?

ashen arch
polar acorn
polar acorn
frosty hound
#

If you feel the need to adjust the base gravity, which is based on true gravity, you probably have your world scale completely off.

calm sierra
calm sierra
polar acorn
#

Perhaps you should actually show !code for context

eternal falconBOT
polar acorn
#

instead of assuming fundamental forces of physics are broken

#

It's more likely that you're doing something that doesn't make physical sense like setting your Y velocity to 0 every frame

ashen arch
#

Snail, can you show us your code for the gravity problem

calm sierra
#

yeah one sec

eager stratus
#

I haven't used delegates and UI buttons in a while, so is there a reason this code keeps giving the same result for each button clicked instead of a unique result?

    {
        //Collect button components and assign handles to them
        for (int i = 0; i < 4; i++)
        {
            GetComponentsInChildren<Button>()[i].onClick.AddListener(delegate { Display("Actor " + i); });
        }
    }

    void Display(string name)
    {
        print(name);
    }```
calm sierra
#

just experimenting a little more

polar acorn
eager stratus
dull slate
#

To avoid getting stuck in tutorial hell would this be a good learning path to ensure I have the basics and a good foundation?

Unity Pathways -> CodeMonkey or GameDevTV -> Create Projects

main spade
#

Update, didn't work

#

Weird because the audio clip is assigned

polar acorn
eternal falconBOT
calm sierra
#

@ashen arch @polar acorn

public class PlayerMovement : MonoBehaviour
{

    public float speed = 12f;
    public float gravity = -30f;
    public float jumpHeight = 3f;

    private CharacterController controller;
    private Vector3 velocity;
    private bool isGrounded;

    public Transform groundCheck;
    public float groundDistance = 0.4f;
    public LayerMask groundMask;



    private void Start()
    {
        controller = GetComponent<CharacterController>();
    }

    private void Update()
    {
        isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);

        if (isGrounded && velocity.y < 0)
            velocity.y = -2f;

        float x = Input.GetAxis("Horizontal");
        float z = Input.GetAxis("Vertical");

        Vector3 move = transform.right * x + transform.forward * z;
        controller.Move(move * speed * Time.deltaTime);

        if (Input.GetButtonDown("Jump") && isGrounded)
            velocity.y = Mathf.Sqrt(jumpHeight * 2f * gravity);

        velocity.y += gravity * Time.deltaTime;
        controller.Move(velocity * Time.deltaTime);
    }

    private void FixedUpdate()
    {

    }```
#

im not even sure what im doing anymore

main spade
polar acorn
calm sierra
#

oh

main spade
polar acorn
# main spade Sure. https://paste.mod.gg/cejkrryitqcg/0

Well, there's two clips that are played off of the same audio source: mainEngineSFX and DashSFX. It could still be "playing" one and not doing the dash (even if it's just playing silence at the end of a clip, it's still considered "playing").

As a quick sanity check, replace that dash line with this:

AudioSource.PlayClipAtPoint(DashSFX, transform.position);

This will spawn a new AudioSource object at the location that destroys itself when the clip ends. It's more performance heavy than re-using one, so if this works we should still see about getting your existing audio source to work, but this can eliminate a bunch of other factors as the problem if it works.

polar acorn
# main spade It worked!

So the issue is the audio source itself. Try putting it back to how it was before, but putting audioSource.Stop(); before you play the dash sound

#

PlayOneShot shouldn't care if something's already playing, but it's worth trying to eliminate that as a possibility

main spade
# polar acorn So the issue is the audio source itself. Try putting it back to how it was befor...

Ok did that with ``` private System.Collections.IEnumerator PerformDash()
{
audioSource.Stop();

 if (!audioSource.isPlaying)
 {
     audioSource.PlayOneShot(DashSFX);
 }
 Vector3 dashForce = transform.right * (dashDistance / dashDuration);
 rb.AddForce(dashForce, ForceMode.VelocityChange);

 yield return new WaitForSeconds(dashDuration);

 isDashing = false;

 // Cooldown before another dash
 yield return new WaitForSeconds(dashCooldown);
 canDash = true;

}```

#

Audio source isn't playing however despite some checks

polar acorn
#

Okay, so it's not that it's getting blocked. Does your thruster sound effect play properly?

main spade
polar acorn
#

Ah, you know what, I just noticed something that I probably should have noticed immediately:

private void ProcessThrust()
    {
        if (thrust.IsPressed() && !isDashing)
        {
            StartThrusting();
        }
        else
        {
            StopThrusting();
        }
    }

You set isDashing to true immediately after hitting dash

#

The very next frame, this is going to call StopThrusting

#

which is going to call audioSource.Stop

#

Which, of course, wouldn't stop the spawned audio source from PlayClipAtPoint, which is why that one works

main spade
#

I see, let me try to set it to true a little later on and not immediately

calm sierra
winter plover
#

yo guys, any idea why this code doesnt work? (no errors, i tried to fix all of it already, the point is when u click e near the table it puts u on it)

using UnityEngine;

public class Pc : MonoBehaviour
{

    public GameObject Player;
    public GameObject Table;

    bool isOnPc = false;

    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        float dist = Vector3.Distance(Player.transform.position, Table.transform.position);
        float radius = 1.3f;



        if (dist <= radius && Input.GetKey(KeyCode.E))
        {
            Debug.Log("E pressed near the table! Moving Player.");
            Player.transform.position = Table.transform.position + new Vector3(0, 1, 0);
            isOnPc = true;
        }

    }
}

hexed terrace
#

what doesn't work.

winter plover
#

well

#

it doesnt change

#

my position to the tables

#

or the tables and the vector 3

#

no errors, but theres also no debug.log printed

slender nymph
#

does your player use a CharacterController?

hexed terrace
#

check the same things that caused the problem last time

winter plover
#

like the whole E pressed part doesnt work

slender nymph
#

ah wait, no log printed means the condition is never true

winter plover
#

yea

#

but why

slender nymph
#

why don't you log useful information and find out?

winter plover
#

i logged update to

slender nymph
#

or better yet use the debugger

polar acorn
winter plover
#

and update worked fine

winter plover
#

i tied everything

slender nymph
#

how about you log something useful, such as the values you are checking

winter plover
#

earlier

#

and it worked fine

slender nymph
#

prove it

winter plover
#

bro what

polar acorn
hexed terrace
slender nymph
# winter plover bro what

prove that the condition works fine now instead of just saying "trust me bro, i logged it earlier"

slender nymph
#

and show the inspector as you've been requested multiple times now

polar acorn
winter plover
#

table object

#

it changes

#

if i move far or close

slender nymph
winter plover
#

going close too

#

dont worry

polar acorn
slender nymph
#

so PROVE THAT. why the fuck would you show a log that makes it clear that the condition is false when you are trying to prove that you are getting close enough to it

polar acorn
#

That distance isn't less than the value you set. So it doesn't run

winter plover
#

i lit

#

went right up to the object

#

and i clicked e nothing happened

#

the distance was litteraly like

slender nymph
#

alright i'm out

winter plover
#

0.02

#

or smth

polar acorn
winter plover
#

like way less

polar acorn
#

why did you show a screenshot

#

of it not being that

slender nymph
polar acorn
#

And expect us to just know that at some point it was okay

winter plover
#

cuz he asked me to specifically print the distance

steady isle
#

how to open animator window in unity i cant find the window tab to open it

slender nymph
#

this is a code channel. but also literally google it

steady isle
#

i said i cant find the window button

#

its not there anymore

polar acorn
calm sierra
polar acorn
calm sierra
#

ah

#

is it print()?

polar acorn
calm sierra
#

ah

#

well pressing jump and the player sits still, isGrounded remains true and moving is impossible afterwards

slender nymph
#

to be fair though MonoBehaviour.print does call Debug.Log so you can use it, but Debug.Log has another overload to provide context to the log which is nice

slender nymph
calm sierra
#

it shouldnt be prevented, i know

#

thats why im so confused

slender nymph
#

see that's the thing, it is not prevented from moving unless something is disabling a component. the code doesn't lie, so show the inspector for the object when this issue occurs

calm sierra
#

also, could it be related to the fact that the player spawns like this?i do not know how the collision just went underground. moving places you higher though, which means it shouldnt be clipping

slender nymph
#

and, to confirm, this is what you see while the issue is happening?

calm sierra
#

yes

#

and before too

#

only thing changin is position

slender nymph
#

is the mesh and other collider a child of this object?

calm sierra
#

i swear man this was way easier in godot for some reason and i knew way less coding at that time

slender nymph
#

remove the collider from taht since the CC is already a collider, that one isn't necessary. and then set its Y position to 0 to match its parent. then adjust the object until it is actually above the ground

calm sierra
#

did that, now isGrounded is always false

slender nymph
#

make sure that is in the correct position now too. you probably had it in a location relative to where the mesh was rather than where the CC was so when you moved the CC (which was the root object) up, the groundChec object moved up too

calm sierra
#

i had to move the collider in the player

#

and then it was lined up

slender nymph
#

no, don't do that. move the mesh to 0 on the Y axis

calm sierra
#

alright, done

#

ill try now

slender nymph
#

make sure everything is set up correctly rather than just moving the one thing then blindly trying to see if it works

calm sierra
#

issue persists :/

slender nymph
#

show the current setup and code

devout otter
#

why am i gettin errors sometimes that doesnt have a source? how can i fix such errors ?

slender nymph
#

and preferably use a better site than pastebin, like one of the ones in the !code embed 👇

eternal falconBOT
slender nymph
calm sierra
slender nymph
#

that's the neat part, you don't

#

make sure your tool handle is set to Pivot and select the groundChec object to make sure it is where you expect. then you can open up the physics debugger to see where your CheckSphere is and make sure it's what you expect

calm sierra
#

this is in the right place, ill do the second thing you said

#

where do i do that?

slender nymph
#

did you start by googling "unity physics debugger"

calm sierra
#

it seems like the collision inside is smaller?

calm sierra
#

i am really demotivated now

#

ive been stuck with trying to get walking and jumping work for the past 3 days at least

night mural
#

now you know why video games take years to make

calm sierra
#

this feels like a unity problem, at least for me

night mural
#

great, then why not use godot?

calm sierra
#

because it runs really bad

#

and doesnt like writing and reading files

#

outside the .exe

night mural
#

sounds like it's not actually easier

silent valley
calm sierra
calm sierra
night mural
#

are you using kinematic character controller?

calm sierra
night mural
#

it's free now

#

give it a go

calm sierra
#

alr

shadow moss
#

so, i'm switching my project's controls from input.getkeydown("") to unity's input action system. Altering my player's movement code was easy, but i've been struggling with the pause menu. I have the menu controller in the ui panel itself, and no matter what i try, the game doesnt bring up the menu even with the keys configured. i'm not sure if i'm missing something obvious or what, any tips are welcome!

short hazel
shadow moss
#

i don't remember writing one, i'm guessing that needs to be in the player controller?

#

here's my movement control script:

short hazel
#

Also I haven't seen this way of retrieving the action, you'd either refer to the C# class generated by the Asset, or by using an input event component (whatever it's called) to forward events

#

Yeah here like in this second script

#

You have the OnXXX(CallbackContext ctx) methods

brave robin
#

-= will remove the method from the action, when you don't want the method listening for the input anymore

#

By using InputActionReference you won't need to find it, you can just select it from the inspector

shadow moss
#

i guess the documentation tripped me up, i was looking at the action workflow

brave robin
#

There's a number of different ways to use the new input system, so at first the documentation will trip you up

calm sierra
#

where do i put in the stuff the package i got from the asset store contains? cant find it

#

i already downloaded it

shadow moss
#

it should be somewhere in your packages folder

rocky canyon
#

when you import a package it'll have a filetree preview that you have to confirm..
it'll tell you there where its going (folders/subfolders) if there's no folders it'll go str8 to the main root asset folder..
if its plugins and/or stuff like that parts will be in those folders

calm sierra
#

ah

rocky canyon
#

decent packages will also have demo scenes with most things set up or there in teh scene.. and readme's documentation

lean pelican
#

I have a projectile with a (1-2 seconds short) lifespan before it destroys itself. Is there any major functional or efficiency difference between using deltaTime or a Coroutine to go about that?

#
{
    //movement stuff
    timeElapsed += Time.deltaTime;
    if (timeElapsed >= lifetime)
    {
        Destroy(gameObject);
    }
}```
#

Or

 {
     yield return new WaitForSeconds(lifetime);
 }```
#

If I start the Coroutine in Start(), is there any practical difference between the two ways?

rocky canyon
#

if by practical you mean visually.. or the result then no..
the coroutine doesn't rely on Update() soo it reduces unnecessary per-frame checks.. biggest difference imo

#

if its a set-it and forget-it moment i'd say use the coroutine

lean pelican
#

Alright, thanks^^

grand snow
#

its not free it still is "checked" each update by unity

small mason
ashen arch
eternal needle
# lean pelican I have a projectile with a (1-2 seconds short) lifespan before it destroys itsel...

I would actually use update here. Im not so sure why others are saying coroutines. The only time id avoid update here would be if the object was just laying around waiting to be "started". Because in that case, you would have to use a guard clause in update to return early, basically checking if it should run or not. You wouldnt have to do that in a coroutine, because it'd only be running when you tell it to. This doesn't seem to be the case for you
it's also a micro optimization but starting a coroutine allocates memory. I see no reason to use one here. A coroutine still does check the condition every frame as rob said

small mason
ashen arch
#

It's also easier to implement any functionality around it, such as pausing the game.

void Update()
{
    if (Game.instance.paused) {
        return;
    }
    //movement stuff
    timeElapsed += Time.deltaTime;
    if (timeElapsed >= lifetime)
    {
        Destroy(gameObject);
    }
}
ashen arch
small mason
eternal needle
ashen arch
#

Can you show your code?

rocky canyon
#

when ur setting the vector for ur lateral movement ur probably setting the Y to 0

small mason
rocky canyon
#

and not letting the gravity do its job

#

need to pass in the velocity it already has along w/ ur movement for the other axis

ashen arch
rocky canyon
#

ur over-writing ur gravity/

small mason
rocky canyon
#

yup, its a common issue.. no code needed lol

#

new Vector3(inputX, controller.velocity.y, inputZ);

#

or w/e combination u need to use

small mason
#

I think I understand the problem now

ashen arch
#

bawsi, can you click on the muscle reaction please

shadow moss
#

it successfully prints out the Debug.log, which makes the whole sitch even weirder

#

wait lol nvm, just fixed it

small mason
polar acorn
small mason
#

I'm aware, I wasn't looking for something specific though so to be brief I posted what I did

real falcon
#

is it possible to mark the triangles used by an agent and add extra cost to them? from what I can tell it is impossible to directly reference navmesh triangles, as well as impossible to set an additional weight modifier on top of a triangle's default area cost...

eternal needle
eternal needle
real falcon
#

wouldn't that override the area type that was set on it previously?

#

I would still need some way to get a list of all the triangles an agent is using for its path as well

#

I saw that there was "get triangulation" or something, but it doesnt really tell you how those verticies are organized so im not sure how I would get the triangles from that

eternal needle
# real falcon I would still need some way to get a list of all the triangles an agent is using...

is there something u need the actual triangles for? i would imagine this is either an XY problem or not a beginner problem at all.
I was thinking something like this for setting the area cost https://docs.unity3d.com/6000.1/Documentation/ScriptReference/AI.NavMeshAgent.SetAreaCost.html
the NavMeshPath just has the corners
https://docs.unity3d.com/6000.1/Documentation/ScriptReference/AI.NavMeshAgent-path.html

real falcon
#

I can't be bothered to figure out what the unity discord considers a "beginner problem or non beginner problem." no matter where I post I get yelled at.

As for why I need the triangles (or polygons, if they aren't all triangles) is because I'm trying to make enemy AI take multiple routes to the player, via the method of increasing the cost of certain nodes that have already been taken recently. If I do it based on nodes though, which would be the vertices of the triangles, then each hallway now has two logical paths, right? one on each edge?

#

setting the area cost from what I read changes the cost of ALL polygons in that "area" tag, like a layer

#

whereas I need to set the cost of individual paths, not entire types of terrain

eternal needle
real falcon
#

it is, but from how I read it, it sets the cost for an area type

#

I have a picture of what im trying to do one sec

final forge
#

Should I be using SerializeField when possible in unity? Or is it better to do a getcomponent call when both are possible? What is good practice here

eternal needle
final forge
#

Okay, thank you

real falcon
#

say the enemy takes this path, I want it to add a cost to all these sectors so that the other enemies will avoid that path, and naturally take the flank routes

high summit
#

Hey! I need to save the float of 'music' on myMixer to a variable just wondering the best way to do this in c#

#

When I unpause I need it to return to the same value so I need to take note of it before setting it to 0

wintry quarry
#

Not two

#

== is for checking if two things are equal

high summit
#

Oh yeah whoops

#

So I have

#
public float savecurrentvolume;
savecurrentvolume = myMixer.GetFloat("music");
#

But i'm ghetting this on 'getfloat'

#

That can only return a bool?

#

I'm lost

eternal needle
grand snow
#

out variables exist to get data out via an argument

real falcon
#

hm, I feel that would be inefficient and prone to potential unintentional overlaps unfortunately, making a bunch of entities. I was planning on making a hashmap of triangles to booleans and clear it every 4 seconds or something like that

#

is there really no way to just increase the cost of a node in the underlying pathfinding calculation?

high summit
grand snow
#
float myCoolVar = 1f;
myMixer.GetFloat("music", out myCoolVar);
#

many ways to use out!

high summit
#

Oh! That's neat

grand snow
#

the point of the function returning bool is so you can check easier if it was successful or not

eternal needle
grand snow
#

@high summit

if(myMixer.GetFloat("music", out float musicVal))
{
    //Do stuff
}
else Debug.LogError("music was not found in myMixer!");
eternal needle
high summit
#

Thanks guys, all working, I need to somehow mute through code but according to the tinterwebs, it's not possible?

open apex
real falcon
#

I could try, im just worried about performance, especially since it's creating a bunch of entities, and I don't know how to measure that performance impact exactly. but maybe as a temporary measure. I like the idea of custom pathfinding, though that will take a while to learn how to do. Plus, can I even do custom pathfinding on the unity navmesh if I can't access its polygons?

open apex
high summit
#

Brains having a hard time trying to figure out a solution to this.

Once you hit pause.

It saves the current mixer volume, and sets it to -100 (essentially muting it)

        myMixer.GetFloat("music", out savecurrentvolume);
        myMixer.SetFloat("music", -100);

Then when you unpause, It sets it to whatever the saved value is, (so it's back to the save volume)

but if i move the volume slider in the settings, it obviously unmuted because it's moving it out of the -100 state, But this means volume comes back in the pause menu.

After some googling, Unity lets you mute the mixer in the editor, but this functionality is not exposed to code so it cannot be done via code (which would fix my issue)

Anyone got any ideas how I can work around this?
(vs muting every single audiosource during pausing)

Thanks!

grand snow
#

Just dont write back the volume strait away?? When you un pause you can restore volume using the new saved value

open apex
high summit
#

okay so this is the slide script

#
    [SerializeField] private AudioMixer myMixer;
    [SerializeField] private Slider musicSlider;

    public void SetMusicVolume() 
    
    {

        float volume = musicSlider.value;


        myMixer.SetFloat("music", Mathf.Log10(volume)*20);
       

            }
#

I need to save the float volume so it can be used in the other script that unpauses

grand snow
#

Do you store user settings anywhere like in a file?

high summit
#

I do not, It's a one time play game without saves

grand snow
#

Then just have some static field somewhere you can read from/write to, e.g:

public class PauseMenu : MonoBehaviour
{
    public static float MusicVolume;
}
#

Probably easiest for you if your current design is messy

high summit
#

Wait so that will connect to the slide scripts float volume?

#

Well fetch

grand snow
#

well if you have a new script per slider just slap it in there

high summit
#

Nice, In slider I have

        public static float MusicVolume;
        float volume = musicSlider.value;


        MusicVolume = Mathf.Log10(volume) * 20;

And then in unpause logic I have

        myMixer.SetFloat("music", VolumeSettings.MusicVolume);

And thanks worked perfect, thanks for the help rob

#

What makes something static? It's a changing value so I find the wording confusing

grand snow
#

means it no longer belongs to instances of a class but to the class name (a.k.a 1 global value)

polar acorn
grand snow
#

snap

eternal needle
# real falcon I could try, im just worried about performance, especially since it's creating a...

Yea sorry this is something I've never done in unity at so dont know what to say there. Pathfinding algorithms arent that complex, all the implementations are available online. I just dont know what data youd use from navmesh and am not on my pc to check. Maybe this is something to ask as a separate question, or a question along the lines of getting agents to take different paths to the same destination.

real falcon
#

dont modifier volumes subdivide the mesh too?

#

but yeah ill try it and see

#

I do think its weird you cant just get a list of individual sectors though

high summit
#

Hey! So i want my scene to start with a black screen then fade into the actual scene. is the best way to do this just putting a black 'image' on a canvas covering everything and then fade it's alpha value with code?

#

Or is there a much easier way im missing

worthy tundra
#

video player wont give me the option to assign an audio source 😿

(the object sits on a prefab)

zealous crater
#

!publisher

eternal falconBOT
#

✒️ If you're an Asset Store publisher looking to apply for that role, please DM <@&502880774467354641> with an image of your publisher dashboard to be added. It may take a week or so to get to your request, please be patient.

worthy tundra
rich ice
#

i just need a quick sanity check. is it not a normal thing for devs to always have the error list open in visual studios? i've been watching some unity devs on twitch and there's a weird amount of them who never even open the error list

polar acorn
#

Ideally, it's always empty

rich ice
#

oh yeah, true lol

north kiln
#

Just press the shortcut that cycles through errors and look at them directly

wintry quarry
final forge
#

Is there a better way to do this? I want to do a dictionary for strings to Tiles in the inspector, but dictionary isn't serializable

rocky canyon
#

i feel like this should be an FAQ, i see this question soooo often.. just worded a bit differently.. or just a slightly different situation.. idk tho

wintry quarry
#

there's some packages that give you a SerializableDictionary, but those packages all do something similar to this under the hood

final forge
#

o ok cool thx

high summit
#

Cant seem to drag my canvas group in here following a tutorial on fading out a canvas

#

Maybe i'm getting canvas and canvas group mixed up

wintry quarry
# high summit

do you have an object that has a CanvasGroup component on it?

high summit
#

That was the isssue, I thought I canvas group was just a canvas grouping stuff inside it lol

#

thanks

ember tangle
#

Is it possible to have two scenes running and have the fixed delta time in each scene different?

strong wren
ember tangle
#

I have this gravity code running in a fixed update:

{
    //apply each gravity wells gravity to each orbiting object
    foreach (var orbiter in orbiters)
    {
        orbiter.rigidbody.AddForce(GetGravity(orbiter.rigidbody, gravityWells));
    }
}

public static Vector3 GetGravity(Orbiter orbiter, List<GravityWell> gravityWells)
{
    Vector3 result = new Vector3();

    foreach (var gravityWell in gravityWells)
    {
        //check to see if object is not itself, maybe not needed, maybe planets are on rails? could cause n-body hell
        if (!gravityWell.gameObject.Equals(orbiter.gameObject))
        {
            // Newton's law: F = G * ( (m1 * m2) / r^2 )
            float m1 = orbiter.rigidbody.mass;
            float m2 = gravityWell.rigidbody.mass;
            float r = Vector3.Distance(orbiter.transform.position, gravityWell.transform.position);
            float gravity = gravitationalConstant * ((m1 * m2) / (r * r));

            Vector3 normalizedDirection = (gravityWell.transform.position - orbiter.transform.position).normalized;

            result += normalizedDirection * gravity;
        }
    }

    return result;
}```

 I was hoping to have a scene in the background running faster to plot the trajectory lines, because the math to do so myself seems quite gruesome.
#

So I would just run the scene like ten times faster and then pause it once I plotted the lines, based on the alternate scene version of each rigidbody.
I'm guessing it just wont work now though.

ember tangle
#

or only the built in physics

strong wren
final forge
#

Hello, I'm trying to understand a good way to make context based user input. Right now, I'm trying to make it so that when the mouse clicks, it invokes an event callback, and so everything subscribed to it will check if the context fits (ui checks if the click is on a ui, tilemap checks context if the player is in a state that allows them to interact with the clicked location, etc). I don't think this will work, since I can't control the order of invocation easily. Should I be handling the context/state checks in the input manager class instead?

ember tangle
keen moss
#

hi

rich adder
#

if you have a unity question just !ask

eternal falconBOT
keen moss
verbal dome
#

So you'd have to call your gravity method manually

hazy furnace
#

Hey everyone, I’m running into an issue with GUI.DragWindow() not allowing my window to be dragged, despite being included in my WindowFunction. My implementation involves scroll views inside the window, and I suspect they might be interfering.
Here’s a simplified version of my setup

private Vector2 LeftScrollArea = Vector2.zero;
private Vector2 RightScrollArea = Vector2.zero;
private Rect windowRect = new Rect(100,500,760,450);

void OnGUI() {
    GUI.Window(windowID, windowRect, WindowFunction, $"Bot Settings {windowID}");
}

void WindowFunction(int windowID) {
    LeftScrollArea = GUI.BeginScrollView(new Rect(10, 20, 225, 400), LeftScrollArea, new Rect(0, 0, 150, 600));
    GUI.EndScrollView();

    RightScrollArea = GUI.BeginScrollView(new Rect(240, 330, 510, 100), RightScrollArea, new Rect(0, 0, 150, 300));
    GUI.EndScrollView();

    GUI.Box(new Rect(250, 25, 500, 300), "Waypoints");
    GUI.DragWindow();
}```The issue: The window remains static and doesn’t respond to dragging. I’m wondering if the scroll views are intercepting mouse input, preventing GUI.DragWindow() from registering correctly.
Has anyone encountered a similar problem? Could it be due to the order in which elements are drawn, or do I need to explicitly handle event propagation? Any insights would be appreciated!
rich adder
hazy furnace
rich adder
shut swallow
#

Is it possible to apply timescale = 0 for all objects except the player

naive pawn
#

what you can do instead is use unscaledDeltaTime/unscaledTime on the player specifically, that'd make it not respond to any timeScale changes

#

or if you need finer control, you'll have to control that yourself

shut swallow
twin pivot
#

is there a rmb version of OnMouseUpAsButton?

twin pivot
#

right mouse button

rich adder
twin pivot
#
    IEnumerator RightClickPlayer()
    {
        if(Input.GetMouseButtonUp(1))
        {
            Debug.Log("functioned");
            StopCoroutine(RightClickPlayer());
        }
        yield return null;
    }
    private void OnMouseEnter()
    {
        StartCoroutine(RightClickPlayer());
    }
#

spaghetti coding rn

rich adder
#

if you gonna use a coroutine for that you'd probably want to use WaitUntil()=> Input.GetMouseButtonUp(1)

twin pivot
twin pivot
#

did i use it incorrectly or do i need to update

rich adder
#

myb

twin pivot
#

thanks

rich adder
#

yield return new WaitUntil( ()=> Input.GetMouseButtonUp(1) )

#

this is basically just calling that function every frame anyway, you can easily use a while loop or update as well

#

there are slight garbage implications of new() a new object each time

twin pivot
#

quick question, how does the new keyword allow me to use WaitUntil as a method?

rich adder
#

so you create a new object that is the instruction that waits an event, this case evaluates a delegate until true

twin pivot
#

Thats very helpful to know, thanks

twin pivot
rich adder
#

and did you test it with a Log prior to the yield?

twin pivot
wintry quarry
rich adder
#

or whatever amount of times you enter collider without release mouse1, you need to place some other checks most likely

twin pivot
#

so what you're saying is that I should add a fallback that detects if the player leaves the collider?

#

also its not detecting right clicks for some reason

rich adder
#

I'd probably use OnPointerUp (you need physics raycaster on camera) and go from there

#

so maybe.. something like cs public void OnPointerUp(PointerEventData eventData) { if (eventData.button == 1) { Debug.Log("Right mouse button released"); }
only quirk is this code goes directly on the collider, the upside is you know it only run on a specific collider
https://docs.unity3d.com/Packages/com.unity.ugui@1.0/api/UnityEngine.EventSystems.IPointerUpHandler.html

Note: In order to receive OnPointerUp callbacks, you must also implement the EventSystems.IPointerDownHandler|IPointerDownHandler interface 🙄

rich adder
twin pivot
valid palm
#

Have you done a file selector? Like the Zelda NES one where you can choose the file (you have created), make a new one or erase. I want to do that with my game. 3 files to load, create or erase.

timber tide
#

Time to learn json

valid palm
#

All right then

shut swallow
#

is it better to use a public static variable or a singleton for a global boolean?

#

or a scriptable object

keen dew
#

Didn't you go through that yesterday already? The answers haven't changed since then

shut swallow
#

just tried using timescale 0

#

failed horribly

#

tried singleton

#

wasn't able to get it working

keen dew
#

That doesn't seem to be related to what you asked first. If you're having problems with code then show it and explain the issue

shut swallow
keen dew
#

Yeah that has nothing to do with global variables

#

If you're trying to make something like a time freeze feature in the game you'll have to design for that from the ground up, it's not something you can do by just adding one variable

ashen arch
# shut swallow is it better to use a public static variable or a singleton for a global boolean...

I always have a gameobject called Game with a script of Game.cs that I use for some global stuff, e.g. bool paused

using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using UnityEngine.InputSystem;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;

[DefaultExecutionOrder(-5)]
class Game : MonoBehaviour {
    public static Game instance = null;
    public bool paused = false;

    void Awake() {
        if (instance == null) {
            instance = this;
            DontDestroyOnLoad(gameObject);
            load();
            init();
        }
        else {
            Destroy(gameObject);
        }
    }
}

// ... other code here
void load() { /* load saved data*/ }
void init() { /* init some stuff*/ }

// Player.cs:
void Update() {
    if (Game.instance.paused) {
        return;
    }

    // other code
}
shut swallow
#

I'm still trying out implementing it

#

I'm struggling to link this to the player script tho

#

since I need to get key down from my character controller

ashen arch
#

Yeah, I have other code in my Game.cs, like:

[Header("Input Control")]
public bool allowInput = true;
public bool isMoving = false;
public bool isMovingDown = false;
public bool isMovingDownward = false;
public bool isMovingUp = false;
public bool isMovingUpward = false;
public bool isMovingRight = false;
public bool isMovingRightward = false;
public bool isMovingLeft = false;
public bool isMovingLeftward = false;
public bool isAttacking = false;
public bool isJumping = false;
public bool isCrouching = false;
public bool isInteracting = false;
public bool isStarting = false;
public bool isLeftTriggering = false;
public bool isRightTriggering = false;
shut swallow
#

when you call it

ashen arch
#

Yeah, just do Game.instance.paused = true; from any script, in my case.

shut swallow
#

or is it private set?

ashen arch
#

instance is public static. and the paused bool is public.

shut swallow
#

so the script is both public get and set

#

ah

#

ok thanks I'll need some time to get it going

ashen arch
#

Okay

north kiln
#

The pattern is called a Singleton, and you should generally use a property to declare the Instance variable so no outside script can set it

shut swallow
north kiln
#

Yes

#

Though Game would be a class, which should be capitalized (Pascal case), as should method names (and even public members if you're following the C# standards, which differ from the Unity built-in members)

ashen arch
shut swallow
#

I currently have this: public void timestopStatus(bool _requestedTimestop)
now, I'm trying to access the code from my character controller which has Timestop = input.Timestop.WasPressedThisFrame() ? TimestopInput.Toggle : TimestopInput.None linked to the code _requestedTimestop = input.Timestop switch { TimestopInput.Toggle => !_requestedTimestop, TimestopInput.None => _requestedTimestop, _ => _requestedTimestop };, so when I do pass my requested timestop and call the function into the singleton, supposingly it should be able to listen to the keydown event

#

that's my logic, at least

ashen arch
#

I dunno, I can't really read your code. I don't use arrow functions, and never seen switch keyword placed like that.

shut swallow
#

it was some recycled code from a tutorial and that's like the only way i know how to do a toggle lol

frigid sequoia
#

If I instantiate an object that automatically becomes a listener of an event, does that object remain within the list of listeners of the action if it's destroyed?

ashen arch
shut swallow
#

oh damn

#

yea I should think of that next time

cosmic dagger
eternal needle
frigid sequoia
#

Mmmm, then I should probably be unsubscribing my buttons when they are destroyed...

eternal needle
#

in some cases it doesnt matter but yea its generally a good practice to always do. especially if you dont know when you should be doing it

frigid sequoia
#

I was actually thinking how I would manage to do like a "cheat death system". Like when hp reaches 0 first send a call to see if there are any "deathcheats" that can trigger and if not, proceed normally

cosmic dagger
frigid sequoia
#

And I was thinking if it might be a good idea to check if the list of listeners was empty to manage that

eternal needle
# frigid sequoia And I was thinking if it might be a good idea to check if the list of listeners ...

it sounds odd that you would specifically be checking if a delegate was empty to decide if the character is dead. It might end up being pretty limiting too though im not sure how you designed the game here. Like lets say before death, your character has some way to cheat death, but only if some condition is true. You would probably want to use the return value of this cheat death method to get a true or false response about if it should still be alive. The method thats subscribed to your event could be handling the actual logic of giving the player more hp

frigid sequoia
#

Yeah, I would want to have different conditions to check if the CheatDeath is triggereable, but mainly this would be on coldowns so suscribing on Awake, unsuscribe on trigger and suscribe again on a timer may work just fine

#

Mainly is limiting for stuff like "I only want this to trigger if the overkill was less than X" for example

#

So I am not sure how I would do that in particular without making a mess of code

#

How could I return a bool on event for example?

eternal needle
#

unsubscribing and subscribing constantly sounds a bit messy imo though it can definitely work. the only real issue i see here, in either case, would be if you wanted to prioritize certain ways of cheating death. you dont really have any control to the ordering here

eternal needle
frigid sequoia
#

I mean, they would be on order of suscriptuon by default, but I don't really care much of the order anyways

shut swallow
# ashen arch if you want to toggle a bool, just do `myBool = !myBool;`
        {

            _requestedTimestop = !_requestedTimestop;
            if (_requestedTimestop && timestopSeconds > 0)
            { 
                Game.instance.UpdateTimestopStatus(_requestedTimestop);
                timestopSeconds -= Time.deltaTime;
            }
        }
        // on Game.cs:
    public void UpdateTimestopStatus(bool _requestedTimestop)
    {
        timestopTriggered = _requestedTimestop;
    }```  is this a correct implementation?
frigid sequoia
#

Worse case scenario I could make like different tiers of priority at which these are called

#

Like CheatDeath1 to 3 and call them in order

ashen arch
shut swallow
eternal needle
ashen arch
shut swallow
#

thanks, it is intentional because I only wanted to update the call when I know there's a valid request

ashen arch
frigid sequoia
shut swallow
#

by a toggle in my script

#
        {

            _requestedTimestop = !_requestedTimestop;
            if (_requestedTimestop && timestopSeconds > 0)
            { 
                Game.instance.UpdateTimestopStatus(_requestedTimestop);
                timestopSeconds -= Time.deltaTime;
            }
            else
            {
                _requestedTimestop = false;
                Game.instance.UpdateTimestopStatus(_requestedTimestop);
            }
        }```
#

this is what I've made pretty quickly

ashen arch
#

Just move the Game.instance.Update line to be after _requestedTimestop = !_requestedTimestop; line

shut swallow
#

so likeif (input.Timestop) { if (_requestedTimestop && timestopSeconds > 0) { Game.instance.UpdateTimestopStatus(_requestedTimestop); timestopSeconds -= Time.deltaTime; } _requestedTimestop = !_requestedTimestop; }?

ashen arch
#

I don't know what you're trying to do. You either want:

if (input.Timestop)
{

    _requestedTimestop = !_requestedTimestop;
    if (_requestedTimestop && timestopSeconds > 0)
    { 
        Game.instance.UpdateTimestopStatus(true);
        timestopSeconds -= Time.deltaTime;
    }
    else
    {
        Game.instance.UpdateTimestopStatus(false);
    }
}

or

if (input.Timestop)
{

    _requestedTimestop = !_requestedTimestop;
    Game.instance.UpdateTimestopStatus(_requestedTimestop);
    if (_requestedTimestop && timestopSeconds > 0)
    { 
        timestopSeconds -= Time.deltaTime;
    }
}
#

oops, edited.

shut swallow
#

the second one I guess, looks a bit cleaner

eternal needle
shut swallow
#

essentially just a toggle for the system, and pass the toggle when it's true and have timestopSeconds

#

otherwise it's false

ashen arch
shut swallow
#

In that case I think method 1 is better

ashen arch
#

I can't say. you'll have to test it, and see how and why you're setting/getting/accessing on the bool from Game.instance.

shut swallow
#

yea, I'm gonna mess around in the editor for a bit and see if it's working as intended

eternal needle
# frigid sequoia Is there really much of a difference from getting the list of listeners from lik...

https://dotnetfiddle.net/Y3IdDI
replace int with bool and this is pretty much what I meant. It's up to you if you want to unsubscribe/subscribe when it's actually valid to cheat death, or just use a return value and check if the value is true. I think either way, you might* need to process this manually. For example if 2 ways of cheating death are currently valid, and you just invoke the delegate, it will go through both methods (possibly putting them on cooldown or whatever side effect exists). This would feel like shit to the user if they had 2 methods for surviving and both get used after dying once

#

also i vaguely recall something something about boxing values in the example i wrote, but im not smart enough to know much about that. I'd assume the alternative of constantly subscribing/unsubscribing would be worse in terms of allocations. Just bringing it up incase you somehow want to research more into this

frigid sequoia
#

Not sure if can do that, so I may just create a manual list of deathcheats and basically call their "OnCheatDeath" method manually

shut swallow
eternal needle
eternal needle
eternal needle
shut swallow
#

doesn't look like I'm missing something

#

I'm pretty sure I set up the singleton correctly

ashen arch
shut swallow
ashen arch
shut swallow
#

it is still coming up empty

ashen arch
#

You'll need to show me what line 168 and 174 are.

cosmic dagger
shut swallow
#

Nope, just a update method

cosmic dagger
#

Also, you need to show us the code from the error lines . . .

#

Look for any reference variables on those lines and check (test) if they are null . . .

shut swallow
#

the system is under UpdateInput which is under Update in the player script, so there should be no problems there

#

Game.Instance.UpdateTimestopStatus(_requestedTimestop); has a null pointer

#

[DefaultExecutionOrder(-5)]
public class Game : MonoBehaviour
{
    //initialise singleton

    public static Game Instance;

    void Awake()
    {
        if (Instance != null && Instance != this)
        {
            Destroy(this);
        }
        else
        {
            Instance = this;
        }
    }

    // handling global variables

    public bool timestopTriggered = false;

    public void UpdateTimestopStatus(bool _requestedTimestop)
    {
        timestopTriggered = _requestedTimestop;
        Debug.Log(_requestedTimestop);
        Debug.Log(timestopTriggered);
    }
}
``` should be working fine, no?
ashen arch
#

Yeah, and you have an object in your hierarchy/scene with the Game.cs script on it?

shut swallow
#

oh

#

lmfao

#

I should attach it to the player

ashen arch
#

I would just create an empty object in your scene called Game

shut swallow
#

ah so when the player is destoryed it wouldn't affect the code

sour fulcrum
#

(A lot of people call it a GameManager)

ashen arch
#

yeah

ashen arch
obsidian kite
#

Hey guys, why is my character controller ignoring the max slope value? Like when a slope is inclined at more than 45° and my character controller max slope value is 40, the player can still go up the slope

#

Im on unity 6.1 2f

shut swallow
#

Can't believe I made such a stpid mistake lol

ashen arch
shut swallow
shut swallow
obsidian kite
shut swallow
#

there's a possibility that some stuff was changed

obsidian kite
#

Then i call the move function

obsidian kite
#

Rn cant talk im in school

shut swallow
obsidian kite
#

A slope

#

So maybe ill just make an alternative idk

#

Like myself prevent the player from moving

#

But if there is a fix ill tzlke it cuz eqsier

shut swallow
#

my understanding is that you could dot product divided by magnitude to get an angle

#

and if said angle is larger than 45 degrees (pi/4 radians) you detect and tell the player not to go up any further

#

I'm not sure how your system is implemented but I use kinematic character motor and the way I do it is this:

                if (motor.GroundingStatus.FoundAnyGround)
                {
                    // check to see if player is in same direction as the resultant velocity
                    if (Vector3.Dot(movementForce, currentVelocity + movementForce) > 0f)
                    {
                        // get the normal of the obstruction
                        var obstructionNormal = Vector3.Cross
                        (
                            motor.CharacterUp,
                            Vector3.Cross
                            (
                                motor.CharacterUp,
                                motor.GroundingStatus.GroundNormal
                            )

                        ).normalized;

                        // prevent movement force that would boost the player
                        movementForce = Vector3.ProjectOnPlane(movementForce, obstructionNormal);
                    }
                }

                currentVelocity += movementForce;```
#

this is under the assuption that you are not on stable ground (dictated by my kinematic motor)

cosmic dagger
shut swallow
#

yea, I did, I felt stupid for forgetting

#

my toggle is fine now... but for some reason if (GameManager.Instance.timestopTriggered) { timestopSeconds -= Time.deltaTime; } is not ticking down correctly

polar dust
#

is timestopTriggered called once, or every frame

shut swallow
#

Oh yea, I wrapped the code incorrectly

#

thanks

grand hamlet
#

could someone help me w VR? please dm me:))

keen cargo
#

Just ask what you need here

obsidian kite
#

Also cant i just get the angle with Vector3.Angle(hit.normal, Vector3.up)?

shut swallow
#

Also I'm not sure how it dictates the rotational angle

hollow pilot
#

How can you load a specific sprite from a sheet into an UI.Image given you have the name of that sprite (not it's index)?

frontImage.sprite = Resources.Load<Sprite>("Assets/Visuals/Cards.png");

^ this doesn't seem to account for spritesheets

Sprite[] sprites = Resources.LoadAll<Sprite>("Assets/Visuals/Cards.png");

^ and this doesn't seem to retrieve my sprites at all

keen dew
hollow pilot
#

Ok, so I moved my spritesheet to the Ressources folder and fixed my path. Now what?

hexed terrace
#

test?

hollow pilot
#

I still don't get how to access one sprite from a sheet using Load()

hollow pilot
#

oh wait, I'm supposed to remove the extension too my bad

#

It worked

#

Why does the extension break it? what if there are two files with the same name and a different extension?

keen dew
#

then it won't work

#

unless they're different types, it probably can differentiate them in that case

hollow pilot
#

Is there a way to retrieve one of those sprites by name from that array instead of by index?

obsidian kite
#

But about the character controller max slope not working, do u know a fix or why it isnt working properly?

hollow pilot
#

It can be used to distinguish ground, slopes, ceilings, etc.

sour fulcrum
hollow pilot
sour fulcrum
#

Ideally you wanna avoid hardcoding stuff in strings like that.

What is the logical reason that makes you want to switch the sprite reference in this context?

hollow pilot
#

The function should take, for example "1D" as a string parameter and update the UI.Image to the sprite I named 1D.

sour fulcrum
#

yes but why

hollow pilot
hollow pilot
sour fulcrum
#

Yes, I'm not saying you can't I'm just trying to work through the solution with you

#

you want to use this function

#

where

#

what conditionally happens to where you would want to use MyFunction("1D")

hollow pilot
#

Basically I'd like to change what cards my player is holding without making new instances of the UI element containing that image

sour fulcrum
#

How do you know you want 1D

hollow pilot
#

I know I want 1D because I have made Enums that provide me with the "1" and "D" parts of the sprite name

#

Each card has a pair of suit and rank from those enums

#

and I wanted to associate a sprite to each combo of suit and rank

sour fulcrum
#

I'm not gonna lie I have not seen enums and attributes used in this kind of way whatsoever. Could be ignorance on my behalf but doesn't feel like the norm

Are you familiar with ScriptableObjects? seems like a very suitable and preferable solution to this kind of stuff

hollow pilot
sour fulcrum
#

no that's pretty much what they are for

#

just on a different part of the disk 😛

hollow pilot
#

So I'm going to end-up with a folder filled with one scriptable object for each unique card in my deck?

sour fulcrum
#

Is this a standard 52 deck? more or less?

hollow pilot
#

It's basically a Mahjong set with more globally known appearances, so less than 52

sour fulcrum
#

Then yeah that's pretty reasonable

#

it sounds abit overkill at first but it's not as bad as you might think

hollow pilot
#

But let's say I decide to add a new field in my scriptable object...

#

I'd have to edit them all one by one?

#

With enums I could mass-edit properties in one neat file, and could do so by rank or suit

#

That's why it sounded like trouble mostly 😅

sour fulcrum
#

There's some third party tools that can assist with it but the short answer is yeah. At the very least this is how Unity has been designed to work best with

#

Never a single objective solution but from what your posting I honestly do believe you'll gain more than you'll lose

hollow pilot
#

In those scriptable objects I can store a specific sprite from a sheet tho... Hopefully I only have to do it once

sour fulcrum
#

and you can reference the scriptableobjects as an asset which can make things super handy

hollow pilot
#

Actually, what's the difference between making a class to contain data and making that class a scriptableobject?

sour fulcrum
#

the fact that it's a serialized preset of a class that is also an asset for drag and drop related reference purposes

#

has more overhead by nature of it doing more for the sake of working better in the editor

hollow pilot
#

I'd never need to drag and drop one specific card's scriptableobject instance, but for editing I see the point

sour fulcrum
#

a specific one no, but we don't have to be limited to only a single layer of scriptableobject usage 😄

#

another scriptableobject to contain a list of your cards for example, can be quite handy

hexed terrace
hollow pilot
sour fulcrum
#

and if you just want a solid reference to all the cards period

#

eg. instead of having your sprites be found as an arbitrary array loaded in a hardcoded string path. you could just straight up have your list of cards be an asset directly referenced by your gamemanager or such

#

then you have a nice clean, non hardcodey way of having a list of all your stuff, not just the seperated visuals

sour fulcrum
#

Ideally however you know you need to display 1D, should also be a way to get 1D

#

if that makes any sense

hollow pilot
#

Well it wasn't, with my card type being a combo of two different enums

#

I needed to combine the info from both to know the name of the sprite

sour fulcrum
#

yes because you didn't have a solid way to link all of that together

lilac cape
#

Is scripting in unity 6 similar to other versions? I'm trying to learn unity 6 and there is this tutorial that only goes up to unity 5 (On Unity Learn):

hexed terrace
lilac cape
#

Good to know, thank you Homer

keen dew
#

That course goes up to 2019.3. It's much newer than 5.x

polar dust
#

why does unity call it scripting?

#

C# isnt a scripting language, code written in a monobehaviour class doesnt seem like youre writing a "script"

#

is it just a leftover from early versions of unity?

keen cargo
#

Though honestly the difference in this context genuinely doesn't matter

#

Scripting is kind of interchangeable here

brave compass
#

But it's also partially left over from earlier versions. There, the distinction between engine and user code was more solid and other languages like UnityScript (a JavaScript copy) were recommended over C#.

grand snow
#

Boo and js weren't used much hence them being ditched

polar dust
#

the only real pet peeve I have about the use of "scripting" is that the standard convention is to name the folder that contains most of the .cs files is called scripts. When the typical thing youd do in most other contexts is for that folder to be named some variation of source or src

#

it took me a long time to get a feel for good project structure, and personally I think scripts made it harder as it pushed the mentality that you need one folder per file type.
whereas now i use source which I can put folders inside to group together relavent parts of the project together, usually the type doesnt matter

grand snow
#

canvas can if in world, ui document cannot as it can only overlay render

polar dust
#

honestly just avoiding putting files into a folder, entirely based on what the file extension happens to be, helps a great deal

grand snow
#

I used to seperate textures and materials then i stopped as its a pain in the ass, i put a model + mat + tex together now

solemn sable
polar dust
#

Good separation for materials is very good too, if some materials are for the terrain, those shouldn't be in the exact same folder as ones for a character

#

At some point I think I had every material live in one folder, and every texture in another. Mixing things like that is a pain

#

its kind of unitys fault for having a pretty featureless way to navigate a project directory

sour fulcrum
#

assets navigation drives me up the wall sometimes

#

i know theres third party implementations but for the love of god some kind of recently viewed selection please

polar dust
sour fulcrum
#

I'd lowkey love to be able to lock folders to a specific parent folder too

#

eg. one tab that might be in some subfolder but that i will always know will be somewhere in my Assets/Project/Prefabs/

polar dust
#

I think an issue is that the project directory in unity has an identical structure to how it would be in a file explorer, you can end up with a a bunch of nested folders in nested folders, and it can feel like a chore to try and group things together because you have to do all that yourself

grand snow
#

UI Elements does not support this rendering mode so its not possible to do it with this without some jank

sour fulcrum
#

i don't mind nested folders. quality of life features can solve a lot of the workflow pains

polar dust
#

theres a game engine called Murder, which seems to disregard the actual structure of your project hierarchy, and instead favours putting things into grouped folders based on tags

#

it would be quite nice to have that in unity

#

but alas

sour fulcrum
#

Not sure if I prefer that tbh. Although ideally Unity could support both

grand snow
#

the search window makes it easier to find certain asset types

misty rock
#

Hey Guys i was watching a tutorial on a player controller, I wrote the exact same script as the guy but it seems like i get an error and he doesnt, can someone please help me? thanks a lot

polar dust
#

true, but I meant that I think the actual structure of where files are located in a file manager, doesn't need to be 1:1 reflected in Unity. It could be nice to group files together in a way that is better than "put them in a folder which is called something specific"

#

like a smarter project folder view

misty rock
#

Oops

#

Thanks guys

#

❤️

wooden minnow
#

i dont even know why this error is happening, please help

Library\PackageCache\com.unity.visualscripting@1.9.1\Runtime\VisualScripting.Flow\Framework\Events\Physics\OnParticleCollision.cs(46,82): error CS1503: Argument 3: cannot convert from 'System.Collections.Generic.List<ParticleCollisionEvent>' to 'UnityEngine.ParticleCollisionEvent[]```
polar dust
#

looks like youre using a list instead of an array

wooden minnow
polar dust
#

oh

wooden minnow
#

unity itself is mad at me and i dont know what i did

slender nymph
# wooden minnow i dont even know why this error is happening, please help ``` Library\PackageCac...

make sure all packages are up to date in the package manager, if the issue persists after updating packages then close the editor, delete the Library folder from within your project, only the Library folder as that is automatically generated by unity, then open your project again. it will reimport all assets and packages then you'll likely need to open your scene again (assuming you had one open)

cosmic dagger
wooden minnow
#

removing the package works

#

i hope i didnt need it

polar acorn
misty rock
#

this is bullying 😿

polar acorn
#

Or a reminder that this happens all the time here as a form of reassurance that you haven't done something wildly off-base.

It's up to you on how to interpret it.

grand snow
#

Everyone was at that stage once. I remember being confused about many things when i began learning programming (java!)

faint osprey
#

does GameObject.Find() find objects that are not set active in the scene

slender nymph
#

!collab 👇 also don't crosspost

eternal falconBOT
#

:loudspeaker: Collaborating and Job Posting

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

slender nymph
earnest wind
#
public Report(ModId modId) : base()
{            
  id = modId;
  ...
}

public Report(long modIdLong)
: this(new ModId(modIdLong))
{
  id = modIdLong;
  ...
}

Is this how you make overrides to a function?

grand snow
#

er no

earnest wind
#

i mean it works?

#

but i just wanna know if i really have to copy the stuff from the func itself

grand snow
# earnest wind then how

You need an abstract or virtual method in the sub class: protected virtual void MyFunc()
then override it:

protected override void MyFunc()
{
   base.MyFunc();
}
#

you dont have to call the base implementation but you can

#

Constructors are different, they do use : base()

earnest wind
#

i just wanted to know if i have to like copy it again, whats inside it

#

so that i have this kind of result i have right now

#

the (+ 1 overload), so i can choose different variables in it yk

grand snow
#

No the base() constructor call will be executed and then your additional stuff

earnest wind
#

but i had a error when the additional stuff was empty tho

#

and it was only once

#

oh wait actually yeah of course it will be once my bad

grand snow
#
public class Foo
{
    private int myInt;

    public Foo(int myInt)
    {
        this.myInt = myInt;
    }
}

public class Bar : Foo
{
    private float myFloat;

    public Bar(int myInt) : base(myInt)
    {
        //Extra stuff
        myFloat = myInt;
    }
}
earnest wind
#

thanks

grand snow
faint osprey
#

ive got a race condition problem kindof where this code

{
    canvasGroup.blocksRaycasts = true;

    if (transform.parent == transform.root)
    {
        transform.SetParent(originalParent);
        rectTransform.anchoredPosition = Vector2.zero;
        MinionManager.Instance.UnassignMinionFromGenerator(minionData, originalGenerator);
    }
}```

calls when i drop my minion and will reset its position if it didnt find a valid drop point

and this is my drop zone code which makes the minion have a parent trying to prevent the reset but due to the other one firing first it doesnt work 
```public void OnDrop(PointerEventData eventData)
{
    MinionDrag draggedMinion = eventData.pointerDrag?.GetComponent<MinionDrag>();
    if (draggedMinion == null) return;

    if(MinionManager.Instance.AssignMinionToGenerator(draggedMinion.minionData, generator))
    {
        draggedMinion.transform.SetParent(generator.minionContainer);
        draggedMinion.GetComponent<RectTransform>().anchoredPosition = Vector2.zero;
    }
}```
scarlet aspen
#

Hi everyone, I have recently started to study programming for unity just trying to figure out where it actually pays to study.
I started with unity learn but i found it bad because it doesn't explain at basic levels the concepts of programming. i tried with the program that teaches c# on microsoft but i would like to try my hand on unity already since some concepts are different, i followed the guides pinned on the channel but some of them take me back to the manual where i wouldn't know where to start... do you have any initial advice? I may be complex but I would like to study well 🙂

cosmic dagger
#

The Beginner and Intermediate scripting tutorials teach you the basics of C# in relation to Unity . . .

cosmic dagger
grand snow
hidden bluff
#

hey i running into a small problem wen jumping im using the new input system and im using (Physics.Raycast) as to check wen my character is on grounded or not. and for the most part is work 100% of the time but now and then my character gets stuck to the ground for a few second before he will jump again

if someone can help or give pointers i would appreciate it.

private void Jump()
{
    ray = new Ray(this.transform.position, Vector3.down);

    if (Physics.Raycast(ray, out hit, jumpCheck, ground) && !MenuManager.instance.gameIsPaused)
    {
        player.AddForce(Vector3.up * jumpHight, ForceMode.Impulse);
        Debug.Log(hit.collider.name);
    }
}
faint osprey
honest mural
#

hi, who can help me with a script that is changing opacity at an ui image if my script debug is showing correct answer?

eternal falconBOT
odd remnant
#

Is there a nomenclature for public functions when it comes to setting or updating values? I know most people use "setX" when they want to set a value to a direct value. What if you want to increase/decrease that value by an amount? Do people use "updateX"? Or is there a better phrase that doesn't conflict with Unity naming standards?

honest mural
polar acorn
honest mural
#

ohh

hexed terrace
#

read it? lol

polar acorn
#

That would also work for += and other special operators depending on type

odd remnant
hexed terrace
#

properties aren't meant to be private

polar acorn
#

Properties are literally designed to be public

hexed terrace
polar acorn
honest mural
#

using UnityEngine;
using UnityEngine.UI;

public class ImageFadeOnFeedback : MonoBehaviour
{
public NumberSlot numberSlot;
public Image imageToFade;
public float fadeSpeed = 2f;

private bool shouldFadeIn = false;
private bool isFading;

void Update()
{
    if (numberSlot.feedbackText != null && numberSlot.feedbackText.text == "Corect!")
    {
        isFading = true;
    }

    if (isFading && imageToFade != null)
    {
        Color c = imageToFade.color;
        c.a = Mathf.MoveTowards(c.a, 1f, fadeSpeed * Time.deltaTime);
        imageToFade.color = c;

        if (Mathf.Approximately(c.a, 1f))
        {
          isFading = false;
        }
    }
}

}

#

is this good

eternal falconBOT
honest mural
#

🙂

hexed terrace
#

you wouldn't use a property in every case of the original question though.

Just use whatever you like and makes sense , it'll be different at each developer.

Increase/ Add
Decrease/ Remove

honest mural
odd remnant
#

Yeah, I don't want to use a direct property setter, because - say - the player may be cursed and their hunger can't increase when curse. I wouldn't want to put that logic on every single other script that increases hunger. I'm going to use a function inside the SurvivalManager to do it.

honest mural
#

fk

#

how am i so stupid

polar acorn
slender nymph
hexed terrace
polar acorn
#
public float Hunger {
  set {
    if (isCursed) return;
    _hunger = value;
  }
}
#

Now nothing else needs to check for the curse. Only this object cares

polar acorn
#

Other stuff just does player.Hunger -= foodValue and the player handles it

odd remnant
#

I understand now. That's actually really cool.

polar acorn
#

It's a pair of functions that use the same syntax as a variable, but it's not actually a variable

#

You'd still have a private field, in this case, a private float _hunger inside the object

#

But you expose a property that runs whenever you change the value using normal variable-assignment syntax

odd remnant
#

And so in my "food" script (I haven't gotten this far, it likely won't be called "food"), I'd do something like SurvivalManager.Hunger += 10? And this would pass "_hunger + 10" to the value?

slender nymph
#

that is, assuming your Hunger property's getter just returns the value of _hunger

odd remnant
#

Right. That makes sense.

#

You wouldn't want it to return some lower/higher value based on some other condition unless there was a good reason for it.

dim egret
#

any way to make an easier looking movement script?

odd remnant
#

Do you need to explicitly include the "get;" function inside the property definition in order for external classes to access it?

slender nymph
#

yes, the property must have a getter if you want to get it anywhere

polar acorn
odd remnant
#

And the snippet above would need a full get definition: get { return _hunger } if I'm understanding this syntax error that VS is throwing. Right?

#
    get { return currentThirst; }
    set {
        currentThirst = value;
    }
}```
dim egret
#

why is a movement script to hard to make 😭

slender nymph
odd remnant
#

Got it.

#

Sweet, thanks!

slender nymph
#

also you are currently returning the property, not a backing field so it will cause a stack overflow

#

oh and you can shorten up the definition a bit with expression body syntax if you want. it looks a bit cleaner

public float CurrentThirst
{
  get => _currentThirst;
  set => _currentThirst = value;
}
odd remnant
#
    get => currentStamina;
    set {
        currentStamina = value;
    }
}``` 
this would still be ok though, given that there's going to be some logic on how thirst increases/decreases. Right?
polar acorn
#

Yep

odd remnant
#

LOL, sorry, switching variables on ya.

polar acorn
#

You don't need both to be expression bodies

#

It's just a shorthand way of writing a one-liner

slender nymph
polar acorn
#

Oh, right

#

Yeah, you need a variable with a different name than the property

odd remnant
#

Ok, mind is breaking a bit. Does the variable in both the get and set need to be the same variable?

#

_currentThirst, that is.

slender nymph
#

it can be the same variable, usually it is. but it should not be the property

odd remnant
#

Ok, understood that part. But external scripts - do they then reference "CurrentThirst" when updating its value?

slender nymph
#

yes, they will use the property not the field

odd remnant
#

Wow, ok. Cool.

#

Intuitive once you get into it, but totally unintuitive to return a different variable name despite OTHER classes setting the property name.

polar acorn
odd remnant
#

So then question about syntax - I see you and multiple others use _variableName. When do programmers use variables beginning with an underscore, and variables beginning with camelcase?

slender nymph
odd remnant
#

Last Q, maybe. It says that _currentThirst doesn't exist in the current context.

#

Where do I need to define it?

slender nymph
#

it needs to be a field in the class

odd remnant
#

OH, its own private field?

#

So CurrentThirst - the property - is kinda acting like a Public class to get/set the private field, _currentThirst

slender nymph
#

correct, the property is really just a getter and setter method disguised as a variable. those getter/setter methods need an actual variable to work on

odd remnant
#

Makes sense.

slender nymph
#

although once we get c# 14 we'll get access to the field keyword for use in properties that can use a compiler generated field like auto properties use

odd remnant
#

I guess then the question I come full circle around to is - why use a Property instead of using public functions? Other than the ease of saying SurvivalManager.CurrentThirst += 10 in another class;

Does it work any differently than saying SurvivalManager.UpdateThirst(10);?

slender nymph
#

properties are just a shorter way to write those getter and setter methods, you treat them similarly to variables but you can change their internal logic without needing to either switch from a variable to a method or have extra methods in the object

odd remnant
#

Ok. And (here's me, laughing at the fact that I said Last Q three Qs ago): inside of my class when I have various logic, should I be referencing the _currentThirst field? Or the CurrentThirst property?

#

My gut says the former, because I may not want it affected by logic in the CurrentThirst setter. But then that seems a bit confusing.

hexed terrace
#

Most likely the property, in case you're doing any functionality in the property

slender nymph
# odd remnant Ok. And (here's me, laughing at the fact that I said Last Q three Qs ago): insid...

depends, if you don't have any validation logic inside the property then it makes little difference which you choose to directly operate with. with the exception of working with structs, a property that returns a struct returns a copy of it, so if you wanted to modify just one property of the struct you'd want to use the field or else you would have to copy the value from the property, modify it, then assign it back

lofty sequoia
#

How would I get the world space coordinates of the corners of this 3D sprite?

odd remnant
#

What about in Saving/Loading? Maybe that's too generic/broad a question. I imagine the player's Hunger/Thirst will be a saved value. And thus when setting it, I don't necessarily want to set it using a piece of logic that, say, checks whether the player is cursed.

queen adder
#

Does anyone have a free character controller script for Unity 6.1?

hexed terrace