#💻┃code-beginner

1 messages · Page 651 of 1

rugged beacon
#

im trying to visualize the generation, is there something like this

 Place(obj);
 Delay(1);
 Place(obj);
wintry quarry
#

I would do something like this:

float angle = 0;
float degreesPerSecond = 50;
float min = 135;
float max = 225;
bool goingUp = true;

void Update() {
  float frameBudget = degreesPerSecond * Time.deltaTime;
  while (frameBudget > 0.01f) {
    float target = goingUp ? max : min;
    float diff = Mathf.Abs(angle - target;
    float toUse = Mathf.Min(frameBudget, diff);
    if (toUse < frameBudget) goingUp = !goingUp;
    angle = Mathf.MoveTowards(angle, target, toUse);

    transform.rotation = Quaternion.Euler(0, angle, 0);
    frameBudget -= toUse;
  }
}```
rugged beacon
polar acorn
bold pawn
#

I'm a bit lost trying to figure out how I would do this. I've got the Skill script as serializable, public fields and all that. But i'm not quite sure how i would add them to the PlayerData script through the inspector. Other than making an empty object with the Skill script for each one and adding those?

wintry quarry
polar acorn
rugged beacon
polar acorn
#

and set it in the inspector instead

polar acorn
#

But it is an alternative to coroutines

#

I gave you the easy one first

bold pawn
#

See i'm not sure what's meant by "set it in the inspector instead". the Player Skills ist is public already, i can add things via the inspector. i'm just.. not quite sure what to add XD

rugged beacon
#

dang so still have to change the the whole function chain then

wintry quarry
#

you should see two fields

#

the int and the string field

#

whatever they're called

#

If you see a single reference field, that means Skill is actually a MonoBehaviour or ScirptableObject

#

which you said it wasn't

bold pawn
#

(i may have changed it to see what happened... lol my bad)

polar acorn
sand field
wintry quarry
sand field
#

Ah I see

bold pawn
#

pfffft yea made Skill not a monobehaviour.. again. figured it out XD thanks folks

prime cobalt
#

For some reason the spherecast is finding both of these despite the fact that it has the same radius as the gizmo which clearly shows they aren't touching...

slender nymph
#

your gizmo is only drawing in place, but your spherecast is being cast an infinite range

#

are you certain you don't want an overlapsphere instead?

prime cobalt
#

oh ok thanks

hybrid kiln
#

Hello, do unity projects normally separate the cs scripts from 3d assets? I've been having no luck looking for this.
This seems like a good practice in my mind since I think git is meant to store code only, but I dunno if I should gitignore the assets since unity create some .meta files for them.
I'm new to Unity so I'm trying to learn how to manage my 1st project, the 3d assets might scale to a very large size later on. Thank you!

timber tide
#

That's the idea unless you want to fess up some monies for git LFS

#

if it's a small project you can probably manage as there's effectively no limit on the size of your repo, but github will send you angry email if it gets too big

#

also pushes tend to fail if file sizes are larger than a gig

night mural
hybrid kiln
#

Thanks! glad I had the right concern. Are there any resources where I can learn more about these practices, or do people just learn as they go?
My team's project is currently pushing assets to the repo so we might need to restructure.

night mural
hybrid kiln
#

I will look into it. Thank you!

nocturne hawk
#

I want my 2D game cam to be further away, how?

wintry quarry
#

what you want to change is the orthographic size.

nocturne hawk
#

It wont let me

wintry quarry
#

what won't let you

nocturne hawk
#

I cant change the value

wintry quarry
#

Are you using cinemachine?

#

You need to change it on the cinemachine camera

nocturne hawk
#

not main camera?

wintry quarry
#

CInemachine camera, as I said

#

the main camera is controlled by the cinemachine camera if you're using cinemachine

#

(are you??)

nocturne hawk
#

yeah

wintry quarry
#

then yes

nocturne hawk
#

oh here, cinemachine camrea lol

wintry quarry
#

You can find the size under "Lens"

#

Also none of this is related to code.

nocturne hawk
#

oh damn

#

where can I ask for stuff like this?

wintry quarry
nocturne hawk
#

I see thx!

tepid summit
#

Is there a way for a script to detect whether or not a controller is connected?

#

Wait nvm I figured something else out

#

No I haven't, back to the original question

naive pawn
#

also, old or new input system?

tepid summit
#

Old system

#

But I've figured that out now, just trying to set up some ps5 binds

tepid summit
#

hey how do i fix my transform gizmo mocing away from my playerobject as i move him again

teal viper
tepid summit
#

not that i know of

teal viper
#

Maybe record a video of what it looks like, because it's not clear what's going on.

tepid summit
teal viper
tepid summit
#

rightio

faint tulip
#

i have this problem where my objects origin was on a empty game object then suddenly after i open the unity editor next day the origin of my game object went from the empty game object to the canvas that was a child of the empty game object

#

what seem to be the problem and the fix for it?

wary elbow
#

im trying to rotate a 2d gizmo but im not sure how to do it. ive found the matrix4x4.TRS function but thats used for 3d andi m not sure if i can use it to rotate 2d gizmos

verbal dome
wary elbow
#

thanks

verbal dome
#

Maybe Gizmos.matrix = Matrix4x4.TRS(position, Quaternion.Euler(0, 0, angle), scale);

shut swallow
#

if i have

{
    CrouchInput.Toggle => !_requestedCrouch,
    CrouchInput.None => _requestedCrouch,
    _ => _requestedCrouch 
};```

how should I implement a toggle to swap between hold to crouch and toggle crouch?
#

Do I implement a _requestedCrouchToggle = input.CToggle switch variable to dictate?

sage mirage
#

Hey, guys! I want to get reference to my volume effects and I am really not sure how to do it. What I want specifically is to get a reference to my motion blur effect from volume component. I am using URP and I am trying to somehow get a reference to it but since its not a component I am not sure how to manually do it because its the only way to actually get a reference programmatically.

#
        motionBlurEffect = mainCameraVolume.TryGetComponent<MotionBlur>(out var motionBlur) ? motionBlur : null;```
#

Thats what I have tried to do but really it isn't a way I think and I am not sure if this works fine. What about the volume the reference is taken for motion blur is the problem

wintry quarry
sage mirage
#

Volume is a unity component

wintry quarry
#

it's more like mainCameraVolume.profile.TryGet<MotionBlur>(out var blur)

sage mirage
#

Motion blur is a volume override

wintry quarry
sage mirage
#

Yes thats the problem

#

I am not sure how to get reference

wintry quarry
#

I just showed you the way

sage mirage
#

and enable disable the motion blur override

#

I dont want to disable the whole volume

sage mirage
#

I did this as well let me try again I think I forgot to use the var keywod

#

keyword

#

because I have seen error to this one as well

wintry quarry
#

those are the important parts

sage mirage
#

No

#

I have used .profile before

#

This code I send is new

wintry quarry
#

You have mainCameraVolume.TryGetComponent<MotionBlur>

sage mirage
#

Yes its new

#

before this

#

I have used maincamera.profile

#

and the code you send probasbly forgot the var

wintry quarry
#

I can't speak to code you haven't shared

sage mirage
#

keyword

wintry quarry
#

you can use MotionBlur instead of var

#

var is just a convenience thing

#

it is identical to writing the actual type

#

you could do TryGet(MotionBlur blur)

sage mirage
#

motionBlurEffect = mainCameraVolume.profile.TryGet(out motionBlurEffect);

wintry quarry
#

no

sage mirage
#

Thats what I did before

wintry quarry
#

that doesn't make sense

#

TryGet returns a bool

sage mirage
#

Yes

#

I think thats why there was an issue

wintry quarry
#

motionBlurEffect = someBool doesn't make sense

sage mirage
#

Do I have to just use an if statement

wintry quarry
#

it's:

if (mainCameraVolume.profile.TryGet(out motionBlurEffect)) {
  // we found it
}
else {
  Debug.Log("There was no MotionBlur on the volume");
}```
sage mirage
#

probably

#

yes

wintry quarry
#

the bool returned tells you if the effect was found or not

sage mirage
#

I can use a bool variable

#

and store the return value to it

#

and then check with if statement

wintry quarry
#

sure, you can do what you like, as long as you follow the syntax rules of C#

sage mirage
#

Yes I just got confused. Anyway, thanks!

#

I have used to drag and drop to tell you the truth and I have never get references programmatically XD

naive pawn
sage mirage
#

He just forgot

mortal jasper
#

Yo chat

unborn valley
#

Does anyone know why it's problematic to instantiate new GameObjects in OnDestroy? It inconsistently makes said objects not clear on scene reload for some reason

wintry quarry
wintry quarry
mortal jasper
#

Ive been looking for a way to make a. Crouch similar to repo

sage mirage
#

@wintry quarry I just figure it out that the issue wasn't only the variable I had declared but also the namespace I was using, which was the one that is used with old post processing system stack v2. So, instead of UnityEngine.Rendering.PostProcessing I should have used UnityEngine.Rendering.Universal because I am using URP instead of Built-in.

wintry quarry
mortal jasper
#

Yo uh chat

#

How van i make a similar crouch to repo

eternal needle
#

It's an issue with how the model was exported. If you make it a prefab you should be able to adjust it but I'd just fix how it was exported. This is a code channel also.

kindred iron
#

guys how can i write here code?

ivory bobcat
#

!code

eternal falconBOT
kindred iron
#

ty

ivory bobcat
#

If there's a lot use an external site and post the saved link back here.

kindred iron
#

Guys whats the best way of movement at coding? I used rb.linearVelocity but its not good for topdown 2d

float horizantal = Input.GetAxis("Horizontal");
float vertical = Input.GetAxis("Vertical");

Vector2 movement = new Vector2(horizantal, vertical);
rb.linearVelocity = movement * speed;
verbal dome
#

Why is it not good?

ivory bobcat
#

There isn't any one way to do something. Maybe describe what isn't working as expected etc

kindred iron
#

and when i use addforce its even worse why?

verbal dome
#

Sliding? Have you tried GetAxisRaw instead?

ivory bobcat
#

The rigid body component was meant to simulate rigid body physics. If you're needing game physics, consider making it kinematic or finding other solutions online

teal viper
#

Maybe also clarify what you mean by "sliding"?

kindred iron
#

when i stop moving it slides

#

it stops moving slowly

verbal dome
#

The only sliding i can think of here would be caused by the default smoothing of GetAxis

kindred iron
#

its just a number

teal viper
#

Well, then there's an issue in your logic(somewhere else). The code should be setting velocity to 0 when there's no input.

verbal dome
#

So did you try GetAxisRaw or not

ivory bobcat
#

If you're assigning the value directly to the velocity as illustrated above, it would be the determining factor as to why your object isn't stopping immediately.

#

If there are other issues with the physics simulation/interaction, you'll have to provide more information.

kindred iron
#

ty for help btw

verbal dome
#

Because GetAxis smooths the input

#

GetAxisRaw skips the smoothing

kindred iron
#

oh i got it ty last 1 more question, should i use * time.deltatime at this code rb.linearVelocity = movement * speed;

verbal dome
#

Nope

naive pawn
kindred iron
naive pawn
#

when you want to convert to "x per frame"

#

like when you're doing something over time

kindred iron
#

wdym i didnt get it

naive pawn
#

if you have a bar that you want to fill (let's say from 0 to 1) over 1 second, you would add deltaTime each frame for 1 second

kindred iron
#

if we dont use rb, we use then time.DeltaTime for getting the same speed in 1 sec

naive pawn
verbal dome
#

rb.velocity is already "units per second", so using delta time is not needed (and wrong)

#

Roughly speaking, multplying with deltatime adds the "per second" part to things

naive pawn
#

(but Rigidbody.velocity is already per second)

verbal dome
#

Well, 0.25 * deltaTime is not 0.25 per frame

#

It is 0.25 per second

#

Thats what i mean

naive pawn
verbal dome
#

Yep

#

Im just trying to express it in a more beginner friendly way

shy cairn
#

hello, may i ask what is the usual solution to have the horizon line up with the water?

grand snow
#

not a code question

shy cairn
#

i cant seem to find any option to have the skybox lower

#

oh

#

sorry ill ask in the other channel

slender nymph
#

and don't crosspost

sage mirage
#

Hey, guys! I got an error of stack overflow and I dont think I know what causing it. When I start the game so I am entering play mode the error occurs and the game is paused.

StackOverflowException: The requested operation caused a stack overflow. UnityEngine.Events.UnityEvent`1[T0].GetDelegate (UnityEngine.Events.UnityAction`1[T0] action) (at <2431722e3e3e41d78b6718bb39ab9111>:0) UnityEngine.Events.UnityEvent`1[T0].AddListener (UnityEngine.Events.UnityAction`1[T0] call) (at <2431722e3e3e41d78b6718bb39ab9111>:0) UnityEngine.UI.CoroutineTween.ColorTween.AddOnChangedCallback (UnityEngine.Events.UnityAction`1[T0] callback) (at

slender nymph
#

if you look at the full stack trace, do you see anything about your own code?

sage mirage
#

Give me a sec

#

Yes I see that I have two errors in two lines of my settings manager script. Let me inspect it probably know whats causing it.

#

@slender nymph I am working on settings by the way with player prefs etc. Do you have anything in mind what is causing the issue?

slender nymph
#

how could i possibly know if you haven't shown relevant code or even said where the issue is occurring?

sage mirage
#

I am working on motion blur setting, so I have made a toggle and trying to make it functional.

{
    if (motionBlurToggle.isOn)
    {
        motionBlurToggle.isOn = inactive;
    }
    else
    {
        motionBlurToggle.isOn = active;
    }
    PlayerPrefs.SetInt("MotionBlurEffectValue", (motionBlur.active ? 1 : 0));
    PlayerPrefs.SetInt("MotionBlurToggleValue", (motionBlurToggle.isOn ? 1 : 0));```
#

When I am commented out this method the error disappears

#

So, probably somewhere here because the lines are showing that the source of the issue is somewhere here

slender nymph
#

you are likely calling this method in the toggle's event which means when you set isOn it calls this method which then sets isOn which calls this method which then sets isOn which calls this method which then sets isOn and so on.
check the docs for the toggle class to see if there is a method or property you could use instead.

livid oasis
#

can someone help me, i cant use " else if anymore and im confused

naive pawn
#

wdym you can't use it?

#

what's the actual issue?

livid oasis
#

im on a new line and need to use else it but eveytime i try to type it it corrects too something else

#

it autocorrects to extendedlistservices

slender nymph
#

are you sure you are doing this immediately following an if statement or another else if?

livid oasis
#

no im not

naive pawn
#

then.. you can't use else

slender nymph
#

well that would obviously be why

naive pawn
#

else always comes after an if

livid oasis
#

no i mean i did use ig first

naive pawn
#

ok, show !code

eternal falconBOT
livid oasis
#

its working now but something is still broken

naive pawn
#

broken how exactly?

#

"broken" doesn't give us any info

#

if it worked you wouldn't be here lol

livid oasis
#

working on it

naive pawn
#

is your ide perhaps not configured?

livid oasis
slender nymph
#

note the errant ;

livid oasis
#

yes i see it

slender nymph
#

that is your issue

livid oasis
#

possible mistaken emtpy statement

slender nymph
#

that is ending the else if statement. so the following block statement is unrelated which is why else if is not valid after it

livid oasis
#

im comepletely new to this so please bare with me

#

ohhhhh

#

so i need to remive it then?

#

remove

#

i seee i seeee

naive pawn
slender nymph
#

also yeah, this is a unity server. general c# questions belong on the c# server

livid oasis
#

thank you fellas im taking a course right now on C# and im having an extremely hard time understanding what this guy is saying

#

can one of you help me with one more thing?

slender nymph
#

is the question unity related?

livid oasis
#

code related

#

ill switch servers

slender nymph
#

is the question unity related because this is a unity server

sage mirage
#

This is not definitely a Unity related issue XD

heavy tinsel
#

can someone help me out? I'm trying to make a test vr game in unity and trying to make a code for teleporting to start when a block is touched but even if the code works it says failed to build

slender nymph
#

start by investigating the first error in the console when you build instead of just focusing on the one that tells you it failed

heavy tinsel
#

theres no errers in the code everythings fine

slender nymph
#

i said in the console

heavy tinsel
#

all it says is Assets\velocitymanager.cs(18,1): error CS1022: Type or namespace definition, or end-of-file expected

slender nymph
#

well that is certainly an error in the code

verbal dome
#

Perhaps some misplaced #if UNITY_EDITOR and #endif

#

Show that part of the code

heavy tinsel
#

can i just send the code

verbal dome
heavy tinsel
#

am i just supposed to put the code there

wintry quarry
#

you're supposed to share it with us

#

we're not mind readers

heavy tinsel
#

ok jeez using UnityEngine;

public class TeleportOnTouch : MonoBehaviour
{
public Transform startPoint;

private void Start()
{
    if (startPoint == null)
    {
        Debug.LogWarning("Start point is not assigned! Please assign it in the Inspector.");
    }
}

private void TeleportToStart()
{
    if (startPoint == null)
    {
        Debug.LogWarning("Start point is not assigned!");
        return;
    }

    transform.position = startPoint.position;
    transform.rotation = startPoint.rotation;
}

private void OnTriggerEnter(Collider other)
{
    if (other.CompareTag("TeleportTrigger"))
    {
        TeleportToStart();
    }
}

}\

slender nymph
#

!code

eternal falconBOT
wintry quarry
#

as per the bot message

naive pawn
wintry quarry
#

Anyway this isn't even the right file

naive pawn
#

oh yeah LMAO

wintry quarry
#

The error message tells you which file it is

verbal dome
#

Show velocitymanager

heavy tinsel
#

i dont think i have velocity manager

slender nymph
#

you have a file called velocitymanager.cs directly inside your Assets folder. what is the contents of that file

heavy tinsel
#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class velocitymanager : MonoBehaviour
{Rigidbody _
// Start is called before the first frame update
void Start()
{
_rb - GetComponent<Rigidbody>()
if (Rigidbody)
}
_Rb.velocity vector3. right;

    {
    
}

}

slender nymph
#

do you just not read the bot messages?

eternal falconBOT
naive pawn
#

that is. very far from valid code

heavy tinsel
slender nymph
#

yeah there are so many things wrong with that

naive pawn
polar acorn
eternal falconBOT
naive pawn
#

but anyways; you said there "weren't any errors in the code", so you most likely haven't configured your ide, see above

wintry quarry
#

And configuring your IDE yes

keen cargo
#

i'm sure the IDE would show at least something in that code? like it's absolute nonsense code even for c# standards

naive pawn
#

c# standards are relatively high standards

polar acorn
#

If it's VSCode it might not even recognize that it is C#

naive pawn
#

this would not parse in js

polar acorn
#

In an unconfigured VSCode it wouldn't surprise me if it was like "Yeah pretty sure this is markdown text"

keen cargo
#

i meant like unconfigured IDE that assumes you're just writing C#

naive pawn
polar acorn
naive pawn
#

well the last valid line is line 9
i think there's enough identifying features to deduce it

#

using, the : for inheritance, top level class

verbal dome
#

Pretty sure that the code is parsed in some kind of chunks anyway, not sequentially

keen cargo
naive pawn
stark ingot
#

Does anyone happen to know why this wouldn't work? I'm trying to figure out how the input manager works with lots of trouble. Instead of moving like expected, I'm getting an error of "ArgumentException: Input Button Up is not setup", but when I have an "Up" setup in my input manager, unless the issue is something else? Here's my code:

private void Update()
{
    //movement
    if (Input.GetButtonDown("Up") && isGrounded)
    {
        rd.AddForce(Vector2.up * height, ForceMode2D.Impulse);
        isGrounded = false;
    }
    if (Input.GetButtonDown("Right"))
    {
        rd.AddForce(Vector2.right * speed, ForceMode2D.Force);
    }
    if (Input.GetButtonDown("Left"))
    {
        rd.AddForce(Vector2.left * speed, ForceMode2D.Force);
    }
}
slender nymph
#

make sure there is no white space in the button name in the input manager

stark ingot
#

There doesn't seem to be any

slender nymph
#

did you highlight the entire name in the input manager and make sure? (press ctrl+A)

stark ingot
#

There's not. I'm using the (I think) default options

#

I didn't make the action map

polar acorn
#

Can you show the "Up" definition in the input manager?

stark ingot
polar acorn
#

This is an Input Actions Asset for the new input system

stark ingot
#

Then what's the input manager?

polar acorn
#

Your code is referencing the legacy Input manager

wintry quarry
slender nymph
polar acorn
#

Do you want to use legacy input, or do you want to use this input map?

stark ingot
#

I didn't realize there was a legacy version, my bad. The newer one would be preferred

wintry quarry
#

Then you'll have to rewrite your code

stark ingot
#

Is this the newer one?

wintry quarry
#

Yes

stark ingot
#

My professor only has outdated slides. Is there a big difference in the code or..?

wintry quarry
#

The new system is more complicated and there are multiple options for how to set it up.

#

The code is very different yes

#

The code also depends on which workflow you choose

#

because there are several

twin pivot
#

If you're just trying to make something functional, i recommend going with the legacy version

stark ingot
#

I'm trying to make player movement with this input system and that's literally it

#

Mostly because this project needs to be done by the end of the week and I don't have time for anything too complex

twin pivot
#

Then yea i recommend the legacy version

stark ingot
slender nymph
#

use the input manager if you want your code to be worse and rely on strings. use the input system if you want something that is more flexible and better

wintry quarry
twin pivot
slender nymph
stark ingot
#

I wasn't aware there were two different systems in the first place

wintry quarry
#

you learn something new every day

slender nymph
#

okay but you're asking repetitive questions after you've already been informed of the difference

stark ingot
#

Yep

#

Sorry

#

I think I'm confusing myself

twin pivot
#

Tl;dr
Input manager is if you need something functional
Input system is if you want something good and permanent

stark ingot
#

Oh I see

grand snow
#

The new one is better and probably best to learn and go with for a long term project

stark ingot
#

The project I'm currently working on is very short term, so I'll be sticking with the older input manager

wary elbow
#

how can i add a sprite to a SpriteRenderer via code, im trying to make circles visible after creating them with new GameObject

wary elbow
#

thanks :D

wintry quarry
wary elbow
#

how can i do that?

quasi rover
#

Hello! Im still trying to get the hang of C# and Unity, so ive been working with a hodgepodge third person controller I converted from a guide and with a state machine. And while that works, Im having the classic problem ofa moving platform that moves up and down at a speed, and when the players on it, the platform falls faster than the gravity, causing a sort of "jitter". Ive been trying to figure this one out, I believe I am supposed to create either a collider to check if the player is on the platform and then modify the velocity, but im kinda lost. Ive tried a few methods but nothing seemed to work really well. Any advice here?

Relevant code: https://paste.mod.gg/ntqxvjdzdlod/3

timber tide
#

Yeah they're a pain. You can kinda get away with childing the character to the platform, but ultimately you do need to sync the velocity between the two units

#

Since you're using rigidbodies, you can use OnCollision methods to grab all colliders that the character is touching which can help you grab the values from the platform

quasi rover
#

So I would get the platform based off the onCollisionEnter, and then id do something on top of the movement to additionally add whatever the velocity is to the rigidbody on top of the current movement code, or something along the lines of that right?

#

Similarly, id have to do the same with the jumping too

timber tide
#

You'd probably grab the current velocity of the platform and just add that to the player's velocity + the current input velocity of the player

#

using forces for the player though is a little tricky if that's how you're doing movement which I'm not entirely sure how to blend it that well together

crude compass
#

Hi, I have a simple question that shouldn't rack the brains of those smarter than me. What alternatives are there to creating movement for a Rigidbody Character Controller. I have this issue where I can't add force to the player because I am constantly setting their velocity to a movement input. I'm trying to add an explosive that launches the player, but I can't due to this issue. Thanks!

quasi rover
timber tide
#

And, if it's not consistent enough, then doing some sort of spherecast may be a better way to keep that collider information going

timber tide
#

You can always just grab the current velocity that's been established from forces used then use that along with the explosive

crude compass
timber tide
#

Depends what you're looking for. If you want drag, friction, and all that jazz that's applied to rigidbodies, then you want to use forces.

timber tide
#

Also physics materials only apply to forces as a lot of these properties would be overriden by setting the velocity

frigid sequoia
#

It's there a way to reassign the references of a script you changed the name of?

#

This kind of stuff I mean

wintry quarry
# frigid sequoia This kind of stuff I mean

Under normal circumstances, if you rename it through Unity or through an IDE with the appropriate configuration plugin, the asset GUID of the script should still be the same so this shouldn't happen

frigid sequoia
#

I renamed with rename feauture by default on Visual Studio

wintry quarry
#

Try renaming it through Unity first

#

it should work

#

Rider handles it properly too

#

I guess VS doesn't

frigid sequoia
#

It renamed the script automatically, but not on the rest of the of places

teal viper
#

VS renames properly if configured for unity correctly

frigid sequoia
teal viper
#

!ide

eternal falconBOT
teal viper
#

Take a screenshot of the VS window with a script open.

frigid sequoia
#

This thing on top u mean?

keen owl
teal viper
frigid sequoia
#

What's the difference between these two?

keen owl
#

oh there was a whole conversation behind this, my bad lol

teal viper
keen owl
teal viper
frigid sequoia
#

The thing is, the script asset did update the name when chaging it on VS, just that it didn't pass the references to the objects that use it

#

So that's pretty weird

teal viper
#

When you put the text editor cursor on the class name, hit F2, rename, and apply it, it should rename everything correctly.

teal viper
frigid sequoia
#

Actually, F2 does nothing lol, I may not have any keybind configured on this

teal viper
#

The metadata needs to have the same name as the script file though(this is what a configured ide guarantees).

frigid sequoia
#

Yeah, that's the window I used, it did not update

teal viper
#

If you recompile a script that doesn't have a metadata file with the same name adjacent, then unity would create a new metadata file and thus new GUID, breaking the references.

slender nymph
teal viper
#

It would work even with auto refresh disabled.

#

The only other thing I can think of is maybe some write access rights issues or something locking the meta file during that time.

frigid sequoia
teal viper
frigid sequoia
#

Should VS script automatically rename the script if I rename it on the editor?

#

Cause it happens quite often when renaming that I the window I am working on gets a missed reference when renaming and I have to open it anew from the editor

slender nymph
slender nymph
frigid sequoia
#

Well, this is absolutely freaking wild

#

Cause I just tested that with a sample script and it did update properly, but it does not with the original script I was trying to change

#

The only difference I may see is that the script is inside a prefab?????

teal viper
#

Must be something locking the script meta file as I mentioned earlier

#

Open the script path in explorer. Do you see a meta file with the same name? Does it seem to be read only in the properties? What path is it in?

frigid sequoia
#

Should be fine?

teal viper
#

And take a screenshot

frigid sequoia
#

Nah, it's not on read only or anything like that

#

It's in spanish, so u have to trust me there lol

teal viper
#

What path is it in?

#

Or rather what path is your project in?

frigid sequoia
#

Mmmm, they are each just next to each other right? Should that be a problem?

teal viper
#

No. I just want to make sure it's not in some weird path like one drive or users directory.

frigid sequoia
#

Not that I know about lol

eternal needle
#

I once also had an issue when renaming with VS. It couldve really just been a hiccup. I'd just try undoing your change if possible with version control and trying again if this isnt common for you

frigid sequoia
#

It would not work with the rest then

frigid sequoia
#

🤷 🤷 🤷 🤷

eternal needle
teal viper
nimble tulip
#

Has anyone used Jetbrains Rider? What other IDE's are out there besides VS and VS Code that you would recommend?

#

Just want to try something different.

wet pivot
#

bit of a pointless question here... I'm trying to get a vector that is rotated 90 degrees to the right and 90 degrees to the left of the player input vector...

// Get a Vector3 to the right and left of the input direction. Vector3 inputRight = Quaternion.Euler(0, 90, 0) * new Vector3(pm.horizontalInput, 0f, pm.verticalInput).normalized; Vector3 inputLeft = new Vector3(pm.horizontalInput, 0f, pm.verticalInput).normalized * Quaternion.Euler(0, -90, 0);

The first line works, but if I switch the order in the second line it doesn't. Why is this?

#

The second case gives the error
Operator '*' cannot be applied to operands of type 'Vector3' and 'Quaternion'

slender nymph
#

the multiplication is only defined in the one way for Quaternion * Vector3, it must be in that order

frigid sequoia
#

I think that's a valid operation?

#

No wait, forget that, I am dumb

wet pivot
#

weird but I guess it is what it is

#

I assume in C# the resulting type when you multiply 2 different types together is just defined on a type by type basis then?

slender nymph
frigid sequoia
#

Mmmm, apparently makes no sense to mutiply a vector3 by a quaternion???

sour fulcrum
#

quatrernions are designed to use vector3s. vector3s are not designed to use quaternions

frigid sequoia
#

Since quaternion is a defined rotation, that can be modified by a vector, but a vector, altho can be a defined position, can also be direction to rotate the quaternion, but the other way around it's not possible?

#

Fuck, quaternions are complex

wet pivot
sour fulcrum
wet pivot
#

quaternions have been the most confusing part of unity code since I got started 😅

#

thanks for the answers

wintry quarry
#

you are overthinking them

#

like most people do

#

just think of them as a variable that holds a rotation

#

don't worry about what's inside

frigid sequoia
#

I just think about them at that arcane language unity and blender convert my old good eulers to actually work properly for a reason I will never understand

#

That's quaternions to me

north kiln
#

The terms are a bit fraught of course, but there's parallels

frigid sequoia
#

So you when applying a quaternion to a vector, you would.... rotate the vector on the direction on that quaternion from the vector 0 as rotating point? That's the operation we would be doing there? Cause I otherwise I don't see how you could apply that

wet pivot
#

watched unity's videos on it and they skipped explaining what they are straight to what you can actually do with them... suffice to say im perfectly fine with not knowing how these actually work

north kiln
wintry quarry
frigid sequoia
#

Doesn't seem to have many applications on unity, given that you can just do that with parenting, maybe that's there was no need to implement that

wintry quarry
#

It's quite common to want to do some rotation math withouit having to rearrange GameObject hierarchies or move Transforms around in the world.

wet pivot
frigid sequoia
frigid sequoia
wintry quarry
north kiln
#

(I forget which direction you need to go when rotating around up, it might be inverted)

#

Why remember a handedness rule when you can just negate it every time you do something atwhatcost

wet pivot
#

in the tutorial I watched, wall detection is based on the camera angle, which works for first person but i'm trying to make a mario style game

frigid sequoia
#

Send a raycast left and right and detect walls nearby

wet pivot
frigid sequoia
#

I don't see the need of any quaternions there?

north kiln
#

You can technically go real lazy mode with this one and do 2D perpendicular maths

#

If the y coord is 0

#

but then you lose some flexibility if you want to do other rotations later. Depends on the needs

wet pivot
#

o snap didnt know theres a perpendicular function for vector2 yea that would simplify things

frigid sequoia
#

You want the character to just literally run up a wall when jumping into one?

wet pivot
#

run parallel to the wall

frigid sequoia
#

Cause you could just get the normal of a raycast detecting the wall and lock the character in to move on that direction

wet pivot
frigid sequoia
#

A run over a walk mecahnic can be done in many ways, but on a 2D game I'd say messing with quaternions it's overkill

#

But hey, if it works, go ahead

wet pivot
#

its a 3d game

wet pivot
frigid sequoia
#

And does your character actually rotates? Cause u could just make it seem like so with animtaions, without ever rotating any actual movable abject

wet pivot
frigid sequoia
#

The animation is relative to whatever you make it relative to. You animate the objects and the parent of all them would be the point of reference

wet pivot
#

my character is currently just the default capsule with a hat and a mustache

wet pivot
frigid sequoia
#

Yeah, u can wrap that on an empty, and then u rotate the capsule as an animation, the player movement would be on the parent, not the capsule

#

But, you can do it in many ways, so not follow my take

wet pivot
somber radish
#

guys, what is most modern way to do 3rd person movement now?

I see many solutions on YT tutorials

Now I use this:

using UnityEngine;
using UnityEngine.InputSystem;

public class Example : MonoBehaviour
{
    Rigidbody m_Rigidbody;
    public float m_Speed = 5f;
    public float m_RotationSpeed = 50f;
    private Vector3 direction;

    void Start()
    {
        m_Rigidbody = GetComponent<Rigidbody>();
    }

    void Update()
    {
        InputAction input = InputSystem.actions.FindAction("Move");
        Vector2 inputDir = input.ReadValue<Vector2>();
        direction = new Vector3(inputDir.x, 0, inputDir.y);
    }

    void FixedUpdate()
    {
        m_Rigidbody.MovePosition(
            m_Rigidbody.position + direction * Time.fixedDeltaTime * m_Speed
        );

        Quaternion targetRotation = Quaternion.LookRotation(m_Rigidbody.position + direction);
        m_Rigidbody.MoveRotation(
            Quaternion.Slerp(
                m_Rigidbody.rotation, targetRotation, m_RotationSpeed * Time.fixedDeltaTime
            )
        );
    }
}
#

and where do I need to add normalized ?
And should I use Slerp for MovePosition too?

twin pivot
#

thats the legacy input manager

#

and also !learn

eternal falconBOT
#

:teacher: Unity Learn ↗

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

verbal dome
#

LookRotation expects a direction and not a position btw, so that part looks wrong at least

somber radish
wintry quarry
#

Yeah this is the new system, not sure why they said that

#

Anyway there's not really a "most modern way" to do movement. Every game has different needs and requirements and different movement styles

crisp token
#

Have you guys seen/used this pattern before?

#

Chatgpt gave it to me for simulating pseudo polymorphism for static variables

wintry quarry
#

it's pretty similar to most "generic singleton" implementations floating around

#

I'm not sure that type constraint makes sense though 🤔

teal viper
#

This is probably bullshit

wintry quarry
sour fulcrum
#

Not trying to be an ass or anything but if your coming in here just to validate a chatgpt result you shouldn't be using chatgpt

somber radish
crisp token
#

I mean the point is that supposedly you could have: MovementSystem : SystemRoot<MovementSystem>, use SystemRoot to define shared behvaiors between systems, and also use SystemRoot<MovementSystem>.static variables for keeping track of initialized systems

#

then again I might be better off just having the service locator or containers manage all instances of each class, but I figured using a static - store like approach per class could make it easier

slender nymph
#

yeah this is pretty much the generic singleton pattern, just using the name "SystemRoot" instead of "Singleton" for whatever reason

crisp token
#

Oh ok; yeah thats because I was initially asking about if static variables in dervied classes of my baseclass SystemRoot would use class state from the base or derived class

north kiln
crisp token
#

they really ought to teach more about design patterns in school

crisp token
north kiln
#

That doesn't make sense to me

wintry quarry
#

Sounds like DI to me

crisp token
#

So like, lets say my server is running code for 10 players, and each player has a movement system class which can really be a singleton if it we were only considering that single player's state

north kiln
#

well it's not a singleton then is it lol

crisp token
#

no lol, ig not. I just mean like a static store of instances

wintry quarry
#

Sounds like a singleton that holds a Dictionary of instances.

north kiln
#

It just sounds like a singleton with another design pattern in it

sour fulcrum
#

There's nothing specific to statics in this context, that just comes down to how you wanna organise your references to game content

crisp token
#

Ok, thanks guys

sour fulcrum
#

(for example, imo having global access to all the player movement systems directly would be weird, you'd probably have access to all the players who each have access to their respective movement controller)

crisp token
# sour fulcrum (for example, imo having global access to all the player movement systems direct...

mhm yeah. Well I'm thinking about doing this: a bunch of SystemRoot clases that are the "roots" of their repsective systems (movement, camera, audio, etc). They all are responsbile for fetching their own external dependencies from other systemRoot classes via a service locator, and then that service locator would provide a way of inputing a player id so you can access all the systems for a specific player. Everything would still technically be accessible in the service locator at once, but it would provide a neat way for the server to only get what it needs via a single id.

sour fulcrum
#

I might be ignorant when it comes to this but it feels abnormal to have those kinds of systems kinda separated like that? why have movement, camera and audio be global access points that requires a player id when you could just have the players be the access point who each have their relevant references

crisp token
#

Thats a better idea

sour fulcrum
#

for those player specific ones yeah

#

something like that plays to inheritance's advantages too since you will likely have the same kinds of systems on a variety of stuff

#

eg. audio on players, enemies, interative objects

crisp token
ivory prism
#

Going through the tutorial I am running into something I am not quite sure I understand

Type collectible2DType = Type.GetType("Collectible2D");
        if (collectible2DType != null)
        {
            totalCollectibles += UnityEngine.Object.FindObjectsByType(collectible2DType, FindObjectsSortMode.None).Length;
        }

I was curious how the UI in the 2D part of the tutorial worked. I looked at the script and it seems to run this code above, but I dont see or understand how GetType works, because the collectables aren't Tagged and i dont see anyway to set a custom Type

stable moat
#

sorry to interrupt but ive been avoiding this and just doing everything but it but when i move my player to the next boundry i have set it looks like its moving but the camera itself isnt ? idk

wintry quarry
#

I have no idea why they are doing it this way, by the way

ivory prism
#

Right, but then how is it getting it correctly?

#

Is this type set somewhere?

wintry quarry
#

they could just do

UnityEngine.Object.FindObjectsByType(typeof(Collectible2D), FindObjectsSortMode.None).Length;```
wintry quarry
#

It's right there in the code

#

They are providing a literal string "Collectible2D"

#

presumably there is a script in the project called Collectible2D

ivory prism
#

Oh so Collectible2D is a script

#

Oh wait duh

wintry quarry
#

it's a class name, yes

ivory prism
#

Sorry, I am slow

#

😭

wintry quarry
#

The preferred way to write this would just be:

totalCollectibles += UnityEngine.Object.FindObjectsByType<Collectible2D>(FindObjectsSortMode.None).Length;```
#

i have no idea why they did it that way

#

I guess so it would compile even if that script was deleted from the project

ivory prism
#

I guess more user friendly to display the use of variables and stuff to newer programmers

#

or that

sour fulcrum
#
public abstract class InspectorField<T> : InspectorField
{
    public override bool TrySetTargetValue(BoxedValue potentialValue)
    {
        if (potentialValue is BoxedValue<T> castedValue)
        {
            SetTargetValue(castedValue);
            return (true);
        }
        return (false);
    }
}

I can do generic type checking like this right? where if the InspectorField<T> in question is a InspectorField<string> and the BoxedValue<T> is a BoxedValue<string> ?

verbal dome
#

Why not take a BoxedValue<T> as an argument directly?

sour fulcrum
#

the thing running this doesnt know

stable moat
slender nymph
#

also consider showing screenshots of the component setup instead of making people watch your mouse wiggling video to figure out what might be wrong

stable moat
#

i was about to do that..

somber radish
#

Why its so laggy ?

PlayerMovement script:

using UnityEngine;
using UnityEngine.InputSystem;

public class Example : MonoBehaviour
{
    Rigidbody m_Rigidbody;
    public float m_Speed = 5f;
    public float m_RotationSpeed = 50f;
    private Vector3 direction;

    void Start()
    {
        m_Rigidbody = GetComponent<Rigidbody>();
    }

    void Update()
    {
        InputAction input = InputSystem.actions.FindAction("Move");
        Vector2 inputDir = input.ReadValue<Vector2>();
        direction = new Vector3(inputDir.x, 0, inputDir.y).normalized;
    }

    void FixedUpdate()
    {
        if (direction != Vector3.zero)
        {
            m_Rigidbody.MovePosition(
                m_Rigidbody.position + direction * Time.fixedDeltaTime * m_Speed
            );

            Quaternion targetRotation = Quaternion.LookRotation(direction);
            m_Rigidbody.MoveRotation(
                Quaternion.Slerp(
                    m_Rigidbody.rotation, targetRotation, m_RotationSpeed * Time.fixedDeltaTime
                )
            );
        }
    }
}
#

hierarchy

twin pivot
#

What do you mean by laggy

somber radish
#

see video above

eternal falconBOT
sour fulcrum
#

they posted the code

twin pivot
#

To answer your question tho, check the physics material

#

Wdym, is that not whats affecting it?

sour fulcrum
#

afaik physics materials won't cause that no

twin pivot
#

Oh i see

#

Im guessing the rotation is only considering 2 axises(is that the plural form) and thats whats causing the issue?

somber radish
#

Also I enabled freeze rotation X+Z
And use these rigidbody settings

wintry quarry
somber radish
wintry quarry
#

there is no "proper" way - it depends on your requirements

#

you could try setting velocity directly

#

or using forces

#

the thing is - character controllers are actually complicated things. If you want something that is not just super basic, it's going to be more than 6 lines of code

somber radish
charred spoke
#

Obligatory just get KCC from the asset store

meager gust
#

like a character controller that sits inline with the physics engine?

#

As everyone else has said, you shouldn't be using MovePosition or setting the position of a rigidbody manually. This defeats the whole purpose of using a rigidbody.

#

You should be driving the rigidbody using .AddForce() calls or setting the velocity directly

#

If you use .MovePosition or .Position, you're forcefully bypassing the physics engine

#

You don't really need KCC. This stuff is pretty easy to do by hand.

#

Also if you want to make your rigidbody controller walk up slopes: easy, just project your movement vector onto the plane of the surface you want to walk on. Butter smooth movement.

somber radish
meager gust
somber radish
#

ah

somber radish
# meager gust A pre-made character controller

and what do you think about my hierarchy ? Is it ok?
I have empty parent "Player" with just rigidbody and script
With childrens: Collider (just empty gameobject with capsule collider), Capsule (I will switch it to player model in future)

meager gust
#

all in 1

somber radish
meager gust
#

then have a child be the visual representation

meager gust
#

I'm pretty tired so idk if thats the best way

#

someone else might come along to help you better

#

@somber radishjust make sure your child doesn't have a rigidbody or collider on it

#

it should probably just be purely visual, until you get everything working

somber radish
formal lily
#

Hey I was told to come here to learn coding so uh….what now?

obtuse knoll
#

Suhhh yes it is in the pins

wary elbow
#

how can i get my mouse position as a float, i tried using mousePosition and also putting it into a screentoviewportpoint

vocal sequoia
#

I need thoughts about this Prefab for our player character, is it too much crammed into one? what should I do otherwise

#

Our game is leaving prototpye stage so I want to do things properly moving forward, also this first game ever 🙂

sour fulcrum
#

Looks fine enough

#

I don’t have personal experience but from what I have read/been told etc. most games that ship end up having very cursed player setups

verbal dome
sour fulcrum
#

It’s the hotspot of game dev arbitrariness that eventually just goes against good code and dev composure

wary elbow
#

also tried getting x and y in their own variables but that also didnt work for me

keen dew
#

The issue is not with the vector, it's that if you pass a vector to Instantiate then you have to pass a rotation as well

#

so Instantiate(myPrefab, mousePos, Quaternion.identity);

wary elbow
#

oooh that works :D weird i cant just pass position

grand snow
#

its because there is not an overload for Instantiate() with only these 2 arguments.
So you have to do (obj, pos, rot)

burnt vapor
#

And this is by design because when you instantiate by position, we should also specify the rotation

tribal fulcrum
#

what's the name of that one website with all the unity code terms and their applications

gentle charm
#

any chance someone could help with this error

keen dew
#

It says the errors are in PlayerMovement.cs

gentle charm
#

that would explain it

eager spindle
#

or the unity documentation?

north kiln
eternal falconBOT
somber radish
grand snow
#

you can try an auto upgrade via Edit > Rendering > Materials > Convert selected blah blah

keen dew
grand snow
#

e.g. go to mesh renderer, find material, select it + others, use menu item to auto update to URP shader

#

or, just use your own materials and not bother doing this

somber radish
grand snow
#

new skill unlocked

cyan totem
#

I have two problems...
what does it mean by "Testing the Internet connection using Speedtest.net" and why its has an error
and "Running the UPM health check" i dont know what this is tbh, pls help me fix it.

grand snow
#

cool terminal but I think that is to verify you have functioning internet

cyan totem
#

Any idea how i can fix it?

cyan totem
grand snow
#

what unity version? could just be old and somehow the installation broke

cyan totem
#

hmm its " 2020.3.32f1 "

grand snow
#

oh shit yea thats super old now, 2022 is the min with free updates

cyan totem
#

oh ok alr i try that out thanks

grand snow
#

try unity 6 if you can and make sure you have a backup if you arent using source control

cyan totem
#

and can i ask these sort of question heere or is there an another channel

grand snow
wooden star
#

can somone quickly vc for a quick bug fix. Its my fist time using unity and im strugaling to referance boolian from another script

grand snow
wooden star
grand snow
#

e.g. if(JumboJoe.joeIsAlive)

wooden star
#

ah

#

is that just for bool

grand snow
#

no its to do anything with something else

#

you may need to read up on c# basics if this is stumping you

wooden star
grand snow
#

do what i did

wooden star
grand snow
#

still a thing in python

#
public class MyClass
{
    public bool myBool = true;
    public int myInt = 5;
}

MyClass c = new();
if (c.myBool)
{
    Debug.Log("myBool is true!");
}

if (c.myBool == true)
{
    Debug.Log("myBool is true!");
}

if (c.myInt == 5)
{
    Debug.Log("myInt is 5!");
}
wooden star
#

im still confused as to why its not accepting ==

grand snow
#

you wrote it wrong

#

the comparison should be INSIDE the brackets

#

but as i have demonstrated, a bool on its own is valid as it is gives a true or false result

#

true == true is redundant so we put just true

wooden star
grand snow
wooden star
#

ive fixed it by removing the semi colon but i dont understand how that works

rare basin
#

first of all, you need to configure your IDE

rare basin
grand snow
#

python user moment (not used to where they go)

keen cargo
#

go through that, then go through !learn

eternal falconBOT
#

:teacher: Unity Learn ↗

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

wooden star
grand snow
wooden star
#

yea i just wana pick it up as a hobby and make a dead cells spinn off kinda thing

keen cargo
#

remember to try doing simpler stuff first

#

the simplest thing being a pong clone

cyan totem
gentle charm
naive pawn
eternal falconBOT
gentle charm
#

i followed it and it did nothign

naive pawn
#

you clearly don't have a configured ide there

#

configuring your ide won't fix the issue, but it's a prerequisite to get help here

#

go do so

keen cargo
#

are you using vscode?

naive pawn
#

no

#

that is not vscode

gentle charm
#

visual studio

keen cargo
#

strange, i was using vs and didn't recognize that lol

#

i was going to say that vscode is trickier to set up

naive pawn
#

is it though

keen cargo
#

i remember having issues with it, which is why i changed to vs (though now im on rider)

#

but yea this is still a configuration error because none of the vector stuff is highlighted

gentle charm
#

the game development stuff is slected in the vs installer and it is setup here i think

naive pawn
#

isn't the "miscellaneous files" at the top there supposed to be the assembly

keen cargo
#

do you have the visual studio editor package installed?

naive pawn
#

what...?

gentle charm
naive pawn
#

it's.. still on screen

#

this thing. it should be your assembly or solution, i forget

gentle charm
#

oh i misunderstood what you meant

keen cargo
#

on unity

#

via package manager

gentle charm
#

yea

keen cargo
#

quite strange, when you choose the external script editor there aren't any other choices?

#

this part

gentle charm
#

it was the only one

keen cargo
#

did you try restarting unity?

#

could also be an editor bug

#

just close down the project + your IDE and start it up again

naive pawn
#

also try regen project files

gentle charm
#

no change

#

tried both suggestions

thick spoke
#

!code

eternal falconBOT
thick spoke
keen cargo
#

what's the error?

thick spoke
#

i created a node script, now i am trying to call it, its not functioning correctly for some reason, i keep getting errors

keen cargo
#

but what do the errors say?

naive pawn
thick spoke
naive pawn
#

yeah that's the second one

#

and that's because you have 2 expressoins directly one after the other

#

you haven't put anything separating them

thick spoke
#

i didnt know where exactly to put em

naive pawn
#

like perhaps a +?

#

though i'd recommend interpolated strings for ease of use tbh

thick spoke
naive pawn
#

nope, not a screenshot

keen cargo
#

google , just looked it up

thick spoke
whole osprey
#

When you hover your mouse over the red squiggle underlines, it should give you some clues about what is wrong.

naive pawn
#

$"string content {valueFromOutside} more string content"

thick spoke
naive pawn
#

makes it easier to read, but still, learn how to read errors and fix them

ivory prism
#

How do you make a first person camera with the new version of cinemachine 3.x?

#

I am noticing a lot of differences, either in how things are labeled or configured now

timber tide
ivory prism
#

My fault

#

Didnt see that

timber tide
#

@acoustic belfry
If you're just looking on how to make a struct that's serializable with an ID that's editable in the inspector you can do something like this:

public class Dialogue: Monobehaviour
{
  [Serializable]
  public class DialogueContainer
  {
    public int ID;
    [TextArea(5, 5)] public string Dialogue = "";
  }
    
  public List<DialogueContainer> DialogueContainers;
  private Dictionary<int, string> dialogueDict = new();

  private void Awake()
  {
    foreach (var container in DialogueContainers)
    {
        if (!dialogueDict.ContainsKey(container.ID))
        {
            dialogueDict.Add(container.ID, container.Dialogue);
        }
    }
  }

  public string GetDialogue(int ID)
  {
    return dialogueDict[ID];
  }
}```
#

Problem with doing it all in the inspector is it could get pretty overwhelming if you're doing some large amount of dialogues

acoustic belfry
naive pawn
#

!code

eternal falconBOT
acoustic belfry
#

thanks

acoustic belfry
#

the issue as seen, is that every line, is on it

timber tide
#

Well, like I was saying I'd just use scriptable objects per dialogue, but hardcoding it like you're doing there is fine. I'd suggest using a dictionary instead of this large if statement though.

rocky canyon
#

or atleast a switch

timber tide
#

only reason I say scriptable objects over doing those container classes is unity's inspector gets slow af the more nested objects that are available

acoustic belfry
#

Oh

sharp bloom
#

Having some trouble with UnityEvents...I have the following logic, when a timer finishes it invokes the event which calls a state transition on my "Game Pieces"

this.GetComponentInParent<GamePiece>().onPieceTimerFinished.Invoke();

Then on my GamePiece.cs itself I have

public UnityEvent onPieceTimerFinished;
void Awake()
    {
    onPieceTimerFinished.AddListener(delegate{SwitchState(moveForwardState);});
    }

Now this works on a single gameObject, but I have multiple in play. Every time a timer is finished, the event is invoked on every single piece. How would I solve this?

#

Don't know how clear this is sorry

acoustic belfry
sharp bloom
hexed terrace
#

yes

sharp bloom
#

Yea RemoveAllListeners() works for me here. UnityChanThumbsUp

coral tundra
#

Yo so this is the fastest fix ever but how do you put a picture (non UI) in 3D, in 2d I just drag it over but it doesn’t work here, I need it as reference for my terrain

timber tide
#

Make a plane or quad and drag it onto that

#

actually may need to make a new material if it doesnt create one itself

polar acorn
#

You could also make a SpriteRenderer manually and assign the image to it

#

SpriteRenderers still work in 3D just fine, they're just flat

#

You might need to change your image type in the import settings from "Texture" to "Sprite" though

sharp bloom
#

Maybe Canvas in world space would help here?

worn hedge
#

Hi!! Im trying to make a minigame for class but the teacher doesnt explain quite well unity programming, and I was looking online for some tutorials. To create a game where the player needs to grab balls and put them into a hole would it be very difficult?? Thankss

eternal falconBOT
#

:teacher: Unity Learn ↗

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

worn hedge
#

ooh thanks

odd barn
#

!code

eternal falconBOT
odd barn
#

Hi friends! I'm using the following code in a private void update method to pause the game. It works perfectly fine, but when I change it to a fixedupdate it doesn't work. I don't think I need it to be in fixedupdate, I'm just really curious to understand why that would cause it not to work.

     if (Input.GetKeyUp(KeyCode.Escape) && !isPaused)
     {
         Debug.Log("pause input registered");
         isPaused = true;
         Debug.Log(isPaused);
     }
     else if (Input.GetKeyUp(KeyCode.Escape) && isPaused)
     {
         isPaused = false;
         Debug.Log(isPaused);
     }
 }
polar acorn
odd barn
#

Oh okay, that makes sense. But I run my player's movement in fixedupdate and it's fine. I use code like this to move the player in fixedupdate

        if (Input.GetKey(KeyCode.W) & !isMoving & !isDead && GameManager.isPaused == false)
        {
            north = true;
            south = false;
            east = false;
            west = false;

            StartCoroutine(MovePlayer(Vector2.up));
        }
#

oh wait, GetKey must not be just one frame

polar acorn
odd barn
#

Oh cool. I get it. Thanks!

coral tundra
#

I made a rough setup of how my terrain should be, how do I smooth it out? the smooth tool makes it look weird an ddoesnt remove the bulky look

slender nymph
astral dock
#

Hi! I'm having an issue and I am unsure if its my IED or if I am going crazy. I'm trying to have a timer display visually and I'm following a sort of tutorial about how to do it and when I added the Timer class, I think it added using system.threading which allows me to have a timer class. But when I try to find the object of the timer it says that system.threading cant communicate with UnityEngine. When I delete sytem.threading it no longer registers my Timer as a class? What do I do here? Am I doing something wrong? https://paste.mod.gg/rcixbmcyiwwe/0

naive pawn
#

it's not your timer, is it lol

#

and it's not unity's either

#

FindAnyObjectByType is only gonna work on components that unity knows how to work with

#

don't just type random stuff and expect it to work lol
try googling "unity timer" or something and see where that leads you

frigid sequoia
#

What's even the meainig of the Z position on a rectransform?

#

Isn't the sorting layer the thing in charge of determining what goes in front of what?

naive pawn
frigid sequoia
#

It is, cause I am trying to move it with a corutine and I have no freaking clue if I should be using vector2 or vector3

astral dock
#

Nvm chat I found this issue it was a captial error and I feel like an idiot o7 thank you for the help!

slender nymph
frigid sequoia
slender nymph
#

huh? how is that even remotely relevant to the choice to use a Vector2 or Vector3?

#

is your actual question "what property am i looking at in the inspector?" rather than "what is the meaning of the z axis"?

random lotus
#

Hi guys, I'm trying to get OnMouseDown() working when clicking on a sprite. I added a BoxCollider 2D, and the game still doesn't recognize my clicks. Does anyone have any ideas?

slender nymph
#

for starters you need to get vs code configured 👇 !IDE

eternal falconBOT
slender nymph
#

and secondly, if you are using the input system you should be using the event system interfaces like IPointerDownHandler rather than OnMouseDown

frigid sequoia
slender nymph
#

RectTransform inherits from Transform so it is inheriting the Position property which is a Vector3. so it has a z axis.

#

that's it. it's no more complicated than that.

random lotus
slender nymph
#

have you configured vs code yet? it is a requirement to have it configured in order to get help here

naive pawn
#

that is not configured

marble hemlock
#

does anyone have any ideas with up with enemyList not showing up in the editor?

polar acorn
marble hemlock
#

everything else just works fine but enemyList is just poof

#

no compilation errors and i did save

slender nymph
#

have you done something silly like disable the automatic asset refresh?

polar acorn
#

Try making a change to the code, saving, then going back into Unity and see if it re-compiles everything

marble hemlock
#

by chance, if i did, how would i check that

slender nymph
#

well you can press ctrl+R in the editor to trigger a refresh, but it would also be in the editor preferences

naive pawn
marble hemlock
#

going to try all 3

#

WHERE

#

oh its a script thats not attached to anything and hasnt been used

slender nymph
#

hooray you have compile errors and probably turned off the automatic refresh

marble hemlock
#

i wasnt getting an error before because it was closed down and has been closed down for who knows how long notlikethis

#

just going to delete it. it no longer serves a purpose

#

🙏

polar acorn
slender nymph
marble hemlock
#

i need to start cleaning up my files notlikethis

#

i was testing different ways to have random enemies spawn in any given room but i wasnt sure whether to put it in another script, or give its own exclusive script. unfortunately giving it its own script would have just made it messier

slender nymph
#

also just FYI, you really shouldn't make every variable a GameObject type, you almost never need that. You should be using the type of component you actually care about instead.

keen cargo
#

hey yall, so dealing with a bit of a nightmare situation with some code logic

so this is the current flow our game goes through in order to respawn a player:

-> Case: Die in gamemanager.cs is triggered
-> which starts monster kill animation in monster.cs & starts player death animation in playerstatus.cs
-> Monster kill animation triggers animation event, where monster.cs restart() is called
-> monster.cs restart() triggers gamemanager's case: ResetLevel
-> Case: ResetLevel calls Room.cs respawn()
-> Room.cs respawn() calls player teleportation

so this isn't designed by me, I'm looking to fix this as the logic is way too tightly coupled, however what's a good option to solve this?

using unity events?

whole osprey
#

Hard to know the details, but the obvious first easy reorg would be to move all of the game-wide changes out of monster and player classes. Seems like it would work much more cleanly in gamemanager.

The monster/player can tell the manager it needs to die, but the manager can then... manage what happens with that request.

keen cargo
#

game-wide changes being something like the monster's position?

night mural
#

why does the player dying trigger a monster kill animation?

keen cargo
#

monster killing the player, first person game

night mural
#

what is it? this is an animation on the monster?

keen cargo
#

yep

rich adder
#

why does monster care about gameManager ?

#

should be other way around

night mural
#

wouldn't whatever animation the monster is playing which did damage to trigger Die already be playing?

keen cargo
#
public void restart()
{
    monsterCollider.enabled = false;
    animator.SetBool("Kill", false);
    rb.constraints = RigidbodyConstraints.FreezePosition | RigidbodyConstraints.FreezeRotation;
    transform.rotation= Quaternion.Euler(0f, 0f, 0f);
    isActive = false;
    player.GetComponent<PlayerStatus>().Reset();
    GameManager.instance.TriggerEvent(Type.ResetLevel);
}

This is the "restart" function on the monster, just to give an example on this mess

rich adder
#

yeah this should not be controlling a player reset and game manager..

keen cargo
rich adder
#

2 extra references not needed, it should be other way aroud, it just throws events that manager listens for to react accordingly

night mural
rich adder
#

monster control a player script messy..controlling game maneger? messy

whole osprey
keen cargo
#

it really is, I wanted to work on some camera logic, and ended up having to clean this up lol

rich adder
night mural
#

I think this is the sort of thing tht playables/timeline were desinged to solve, but I haven't really played with them

keen cargo
#

let me post what the gamemanager looks like right now

rich adder
#

You need to look into observer pattern, and just fire some events

keen cargo
#

oh wow, that one kind of messed up the formatting

#

the Events calls is what i've been starting to work with to clean this up and start to use the observer pattern

rich adder
keen cargo
#

hooo wee, looks like i'll be staying up for this

whole osprey
#

It's hard to know what all is listening to those events firing from your game manager, but seems like it is mainly your only Monster and Player classes. Just call the methods from the manager instead of firing events back and forth.

keen cargo
#

gotcha, do you think I should keep the Events as its own file, or insert what I have in Events into the game manager?

public class Events : MonoBehaviour
{
    public static Action OnPlayerDeath;
    public static Action OnPlayerRespawn;

    public static void PlayerDied() => OnPlayerDeath?.Invoke();
    public static void PlayerRespawned() => OnPlayerRespawn?.Invoke();
}
#

or more so i'm asking, which of these is 'best practice' - or does it even matter?

rich adder
#

eh thats just an extra abstraction not needed imo

whole osprey
#

Well, it totally depends on how you structure everything, really. What I am saying is you don't need any of that Events stuff in that little snippet.

You already have your player and monster assigned in the inspector, so call the methods on the player and monster.

rich adder
#

perfectly fine to keep it in the player itself

#

enemy just needs a Public method kill or whatever on player then invoke death event to restart, call anim or whatever from manager

keen cargo
#

alrighty, thanks guys!

#

now to sift through this nightmare and make sense of it, there's oh so many issues

whole osprey
#

Some other easy things to get some other improvements I can see:

  1. Change your GameObject assignments for monster and player to be their classes. Then you won't need to call GetComponent<> on the class you want. It will already be assigned. This also helps ensure you assign the correct thing.
  2. If you make something like that Events class later for some reason, it has no reason to be a MonoBehaviour, so just keep it as an independent class.
keen cargo
#

So something like

[SerializeField] PlayerStatus player;
[SerializeField] Monster monster;

?

Another thing to mention is that the player has a few more classes:

  • PlayerCamera, for camera and body rotation with the mouse
  • PlayerInteraction, for the interaction functionality
  • PlayerMovement, for movement
  • PlayerStatus, for when the player dies

not sure if that matters for that assignment?

rich adder
whole osprey
#

Just for whichever class you need to be calling from the manager.

keen cargo
#

I know we don't have anything that explicitly destroys any object in the game

rich adder
rich adder
#

if there are thing that spawn at runtime or something , then you can use a static event there to invoke itself to the game manager

keen cargo
rich adder
#

the enemy / player shouldnt care about manager

keen cargo
#

i see i see

rich adder
#

they just say "hey I did this" , and game manager reacts " okay im going to do this "

keen cargo
#

thanks! gonna go try this out

frigid sequoia
#

Can I have like an event to notify if a value changes on the same frame? Cause I have absolutely no idea when something is turning null, but doing logs on update is not very useful in this case...

slender nymph
#

You can have whatever you have the skill to make.

frigid sequoia
#

Yeah, then I don't have much lol

slender nymph
#

If you need help with something then you should consider providing actual information about the issue

frigid sequoia
#

This code works wonders when used just within itself, but I have a UI element that can set the draggedWaypoint from outisde it, and it works, until the last part, apparently something is making the dragged waypoint null before reaching the GetMouseButtonUp(0) part, thus not triggering any of that

#

Basically, if you click on the UI, it just spawns the point on top of the cursor and starts moving it, no matter where it is. The move part works, but the dropping does not

honest haven
#

I have a button that I’m setting even system current on and in the debug it’s the correct button but the sprite swap is no highlighting it works fine on all my other buttons but I don’t no why on just this one button

slender nymph
eternal falconBOT
frigid sequoia
#

I don't see anything that would set it to null in there mmmm.....

slender nymph
#

what about anywhere else that would be accessing that variable?

frigid sequoia
#

Oh, I was calling to drop it from an outsider OnPointerUp for some reason

#

I guess it's calling that first

elfin isle
#

anyone know what channel i would go to for problems with a video player?

slender nymph
elfin isle
#

im preety sure itd be here but i can still ask there sure

keen cargo
#

so quick clarifying question about the observer pattern,

if i'm going for an implementation that makes the GameManager into a subscriber, and the Player into a subject, do I understand correctly that it would go something like this:

// Player
public event Action PlayerDied;

public void Die()
{
  // blah blah blah
  PlayerDied?.Invoke();
}

// Gamemanager
[SerializeField] Player player;

Start()
{
  player.PlayerDied += HandlePlayerDeath;
}

HandlePlayerDeath()
{
  // do something here
}

and do I understand correctly, that once Player calls the Invoke, it sends a message to GameManager to execute HandlePlayerDeath()?

wooden star
#

When i start the game the timer is stuck on zero and i doubt it would tick down

keen cargo
#

why are you negating Time.deltaTime?

wooden star
#

its a count down timer

polar acorn
#

It's just always going to be that

keen cargo
#

basically you are just telling currentTime to be Time.deltaTime, but negative

wooden star
#

so it should be time.deltaTime - 1

polar acorn
#

deltaTime is the amount of time, in seconds, that the last frame took to render

wooden star
#

i meant to put "?" sorry

polar acorn
#

So, if your game is running at a stable 60 FPS, you can just pretend Time.deltaTime is the same as writing 0.0166f

#

Setting it to 1 - Time.deltaTime would be basically setting it to 0.9834. What does that accomplish?

keen cargo
#

these docs have an example on a timer too

polar acorn
#

If you want a timer to tick down every frame, and you have a value that holds the time that frame took, what do you think you should do with those numbers?

wooden star
#

wait so it should be curentTime = curentTime -1?

#

but i make it do that for every second elapsed

keen cargo
#

nnnnooooo

#

look at the docs i sent

polar acorn
#

Update runs once per frame

#

currentTime = currentTime - 1 in update means that it is counting frames

#

not seconds

#

If you want it to tick down every second, and you have a function that runs once per frame, you'd need a value that represents the amount of time in seconds each frame takes to load

wooden star
#

i wana try figure it out without looking at the docs but i will if i have to

polar acorn
#

Now, where might you find that

keen cargo
#

everybody looks at the docs, even seniors

#

it's a completely normal thing to do

wooden star
polar acorn
wooden star
#

how long it takes to load a frame

#

well

keen cargo
#

he said that too

wooden star
#

the last frame

polar acorn
#

So, if you have a function that runs every frame

#

and you have a value that is how long that frame took in seconds

#

And you want to measure the passage of time in seconds

#

What might you do

wooden star
#

maths but im half asleep so im stumped

keen cargo
#

brother, look at the docs

#

it's very very simple, you'll be surprised how simple it is

#

no additional lines or anything

#

your implementation is almost there, just one little thing to change

polar acorn
# wooden star maths but im half asleep so im stumped

Let's think of it this way.

You are in a car that is moving at 60 miles per hour.
Every hour, you want to write down how far you've travelled. You can look at the number you wrote down last time.
When it comes time to write down the number, what math do you do to figure out how far you've gone?

wooden star
#

oh

polar acorn
#

You have your speed and you have your distance travelled

wooden star
#

yea im stupid ive just looked at the docs

#

say the delta time was 0.1s and i wanted to increse smth by 1 per s i would just do 1 * time.deltaTime

#

idk tho i am half asleep just tryna get this done before i go to bed

polar acorn
keen cargo
#

no, you'd just be multiplying it by 1

#

wouldn't it be 1 + time.deltaTime?

wooden star
polar acorn
#

It'd be n += x * Time.deltaTime where x is however much you want to happen per second

wooden star
#

ah thanks i get it now

#

dont mind it not being animated i spent 2h as it is making the character and i cba to do it another 50x yet

wooden star
#

one last thing before i call it a night