#💻┃code-beginner

1 messages · Page 143 of 1

idle elk
rocky canyon
#

👍 much better

rocky canyon
idle elk
rocky canyon
#

did you debug the values of the player pref variable to see if it is what u believe it should be?

idle elk
#

yup

rocky canyon
#

which variable is it? that should be loading into the game?

#

or which playerpref value are u working with?

idle elk
autumn arrow
#

im mby stupid but how do i prevent dealing damage while in the trygger i want to deal the damage only once and i have to reenter the trigger

rocky canyon
#

youre using the correct one..

#

OnEnter happens only once during the first interaction with the trigger

#

OnStay would happen every physics frame that you are in the trigger

wintry quarry
autumn arrow
#

well it will deal damage even tho it is in the tigger

rocky canyon
#

then it might be exiting and entering over and over

#

u can test it with simple primitive shapes.. u can drag a box into the trigger, it'll only happen once..

#

its probably ur setup and colliders, like praet mentioned

autumn arrow
#

the second i touch the trigger the hp go down extremly fast

rocky canyon
#

are u sure there isnt other scripts?

#

or the script isnt being disabled and re-enabled over and over?

autumn arrow
#

only this

#

youtube

#

brackeys

rocky canyon
#

so "Enemy AI Found and Damaged" debug is happening over and over too?

#

!learn

eternal falconBOT
#

:teacher: Unity Learn ↗

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

autumn arrow
#

nope

#

so its becous of the method

#

ye

#

and a lot of projects

#

i dont much tho mostly use Tutorials

rocky canyon
# autumn arrow nope

has to be.. if that debug doesnt go constantly.. then its not the trigger that happens over and over

autumn arrow
#

then i nead to ind a way to call it only once pre enter

rocky canyon
#

very weird.. is ur TakeDamage() function called anywhere else?

#

in an Update loop of something

autumn arrow
#

no

rocky canyon
#

idk that doesn't make sense tbh, why would the function be running more than once..

#

but not the trigger that calls that function?

wintry quarry
#

the stack trace will show it

autumn arrow
#

in here

#

nice i fixed it

#

it was me being stopid

#

i forgot that i had dmg on the weapon set to 999 cus i was stesting somethign else

#

and i was just oneshoting the objects but beacous of the Invoke it was destroy them later thats why i thout they were geting kiled while inside the trigger

idle elk
idle elk
#

Idont know why the stone dont display while debug " stone display"

honest haven
#

any one?

rocky canyon
#

debug ur outputs and make sure they're getting modified with the values u expect..

#

then.. make sure ur animations arent controlling its position (overwriting ur code)

#

if its set to "Root Motion" the animation will overwrite the translation u use in code

honest haven
#

thanks

rocky canyon
#

just to be extra sure.. the better way to do it.. is to have a parent root object.. thats the object you move in ur code.. the animation and stuff should be Graphics.. it should be seperate from the logic.. and a child

#

iso u animate the graphics in the child.. but u move the parent container thats containing that child..

#

the animated graphics will just follow along.. b/c of being parented

honest haven
#

awesome. understand

rocky canyon
rancid pelican
#

hello hello! So i'm in the process of creating a fangame, but i'm having an issue with the main menu. I'm trying to recreate Danganronpa's way of using a "Press Any Key" function to get the actual main menu options, but i can't figure it out?

zealous oxide
#

Hey friends, i'm trying apply a force to a projectile based on a vector2 that is made up of the right analog stick axis' on a controller and my issue is that if the analog stick isnt moved to an edge, the projectiles generated are slower. I'd like to make sure all the projectiles are moving at the same speed. I get that the vector2 figures will be anywhere between -1 to +1 and having a vector2 thats like 0.2,0.01 will make the projectiles slower than something like 0.75,0.75 but im not sure what my options are here. The only other alternative i've thought of is to generate the projectiles moving Vector2.right but possibly rotate them?

idle elk
rocky canyon
#

but i think its something about the way u try to save the build index with the string..

rancid pelican
idle elk
#

Can you suggest another way to savs it? And appear in another scene ?

rocky canyon
#

have you seen any of those PlayerPrefs assets in the Unity Asset Store

#

some of em has a window that u can look at that will show ur player prefs

#

it can help you debug

timber tide
zealous oxide
rocky canyon
#

I use JSON and Serialized Data.. but thats pretty advanced for saving a random integer

#

like this one

idle elk
#

Orite tq i will try

rocky canyon
#

can help u visualize the playerprefs that ur modifying

#

instead of just trying to guess and having to debug the values all the time

#

it may help ya find a solution

#

if not just keep asking..

nova swift
#

Anyone got any tips to deal with this stuterring?
It all seems to work pretty well physics wise, just not visually.
This is how I'm moving the player and the platform:

        if(xMovement != 0)
        {
            float t = Mathf.SmoothStep(0f, 1f, Mathf.PingPong(Time.time * speed, 1f));
            Vector2 newPosition = Vector2.Lerp(startPos, endPos, t);

            // Calculate the delta position
            Vector2 deltaPosition = newPosition - (Vector2)transform.position;

            // Move the platform
            transform.position = newPosition;

            if (playerOnPlatform)
            {
                // Move the player along with the platform without interfering with velocities
                playerScript.rb.position += deltaPosition;
            }
        }
dark oak
#

Guys, how can I use input.GetAxisRaw for player control in unity

wintry quarry
#

You use it however you want to control your player object

#

The details of that are bespoke to how your player and your game works

dark oak
wintry quarry
#

sure, why not

#

Maybe look up some tutorials for FPS character controllers

dark oak
dark oak
wintry quarry
#

But, ok.

gusty hazel
#

how can i add a dahsing fearue if my movement works like this, would this work

if (Input.GetKey (KeyCode.RightArrow) || Input.GetKey (KeyCode.LeftArrow) || Input.GetKey (KeyCode.A) || Input.GetKey (KeyCode.D)) {
            transform.Translate (Input.GetAxis ("Horizontal") * Time.deltaTime * speed, 0, 0);
        }
        if (Input.GetKey (KeyCode.UpArrow) || Input.GetKey (KeyCode.DownArrow) || Input.GetKey (KeyCode.S) || Input.GetKey (KeyCode.W)) {
            transform.Translate (0, Input.GetAxis ("Vertical") * Time.deltaTime * speed, 0);
        }
wintry quarry
#

and no, the link would not work

#

you cannot mix Rigidbody motion with transform.Translate

desert elm
#

it seems I have a problem with a stack overflow
with the recursion, where for some reason, it gets repeated
and Now i can't even run the game without getting a stack overflow, even after restarting the engine

wintry quarry
#

You probably should start the new raycast from slightly further along in the original ray's direction

rocky canyon
#

theres different solutions.

#

actually it could be just ur camera.. can use cinemachine to follow ur target smoothly..

#

also has more options

desert elm
wintry quarry
desert elm
#

yeah ill do this

nova swift
rocky canyon
#

well i dont think its the rigidbody.. its not the rigidbody thats jittering

#

its the camera.. now that might happen if its parented to the player..

nova swift
#

It's not parented for one

rocky canyon
#

but interpolation smooths out the movement of a rigidbody

nova swift
#

Ah, I've already got that turned on unfortunately

rocky canyon
#

it basically takes where it is.. where its going.. and finds a middle ground

desert elm
#

and this is also a weird error

rocky canyon
#

cinemachine is built into unity.. just need to go into the package manager get it..

#

im sure with its features u can get a smooth follow

desert elm
#

since armor, maxHealth and health are all public bools in Unit

rocky canyon
#

it has a great section of options for 2d scrollers just like this..

#

with deadzones and whatnot.. to keep the chracter int he center

nova swift
#

I'll try making the camera idle and see if the issue persists to see it's my camera movement that's the problem, because I actually stoped using cinemachine because i wanted to accurately recreate the camera from the sonic classics in 90s

thorn holly
rocky canyon
# nova swift I'm interested on rigidbody interpolation, since i'm not sure what you mean by t...

Let's set up a 2D Camera to follow the player without writing any lines of code!

● Project Files: https://github.com/Chaker-Gamra/2D-Platformer-Game
● Playlist Link: https://bit.ly/3dg1X88
● Game Assets: https://bit.ly/3xVVLtJ

♥ Don't Click This! : https://bit.ly/2Zi3vu9
♥ My Second Channel: https://bit.ly/3jvI8g6
-----------------------------...

▶ Play video
#

check out this video..

#

u can see things like damping

#

which would totally help ya out

nova swift
#

Yea I made the camera idle issue still persists

rocky canyon
#

hmm may have to code in a solution then

nova swift
#

Yea I guess so

rocky canyon
#

moving platforms are always a PITA

nova swift
#

yea haha, thanks for giving a response though, appreciate it

thorn holly
#

Is your ide set up correctly?

rocky canyon
#

integrated development editor

#

or something like that.

thorn holly
#

The place where you write the code

rocky canyon
#

its ur code editor.. VStudio VSCde

thorn holly
#

Well yeah, but will it auto finish your code and highlight errors and stuff?

rocky canyon
#

ur error is here tho..

#

see if u can figure it out

#

^ ding ding

thorn holly
#

Then your ide isn’t set up right

languid spire
#

rb.AddForce(speedright * Time.deltaTime, 0, 0,);
one , too many

thorn holly
#

!ide

eternal falconBOT
rocky canyon
#

heres a visual guide if thats ur taste

#

for visual studio ofc, if ur using visual studio code, you'll have to use a different source

desert elm
#

could just copy/duplicate a script?

rich adder
#

likely the type doesn't match the component or you're putting a scene object onto a prefab not in scene

wintry quarry
#

TextMeshPro is the 3D text version. It's unlikely you're using that

slender nymph
#

use TMP_Text for the variable type

wintry quarry
#

you probably want TextMeshProUGUI. But it's usually best to just use TMP_Text since that covers both of them

rich adder
#

put the correct type TMP_Text

harsh hemlock
#

Hi, anyone know why this text(TMP) isnt showing up in the actual game?

slender nymph
#

not a code question. but it's also not on your canvas

wintry quarry
harsh hemlock
slender nymph
#

check the docs pinned in #📲┃ui-ux to learn how the canvas works and how to set up your UI

merry spade
#

when I rotate my capsule in the scene the arrows for the z y and x pos doesnt turn with the rotation

#

why is that?

slender nymph
#

your tool handle is set to global rotation instead of local

#

and not a code question

merry spade
#

oh sry but thank you

upbeat stirrup
#

how would i offset a prefabs position by a vector3 taking account for the rotation?

slender nymph
#

use transform.TransformDirection and pass in your desired offset direction. but make sure to call that on the object whose rotation you want to account for. then you can just add that new direction to the position

timber tide
#

do you mean offset it such as the rotation would be considered 0 rotation when considering position?

upbeat stirrup
#

if the z rotation is 0, Vector3(0, 1, 0) would move it up, and if rotation was 180, same vector would move it down

slender nymph
#

if the object is not rotated then 1,0,0 would move it right, not up

wintry quarry
rocky canyon
#

just dont modify the rotation...

#

add the vector3 to the position as the offset.. the rotation will remain the same

rocky canyon
#

rotation is global.. localRotation is local

timber tide
#

z+ is forward
x+ is right
y+ is up

slender nymph
upbeat stirrup
#

alr, thanks!

stable ore
#

whats wrong with this

#

im so confused

undone rampart
#

you have 2 scripts with the same name

wintry quarry
#

both of them define class PlayerMovement

stable ore
#

what line

wintry quarry
#

a different file

#

You have two scripts defining the same class.

stable ore
#

im following tutorial rn its from 2 years ago

#

might be outdated that y idk

wintry quarry
#

no

#

it's not outdated

#

you made a mistake somewhere

stable ore
subtle hedge
#

if i want to add arms to my fps character, how should i start, should i add for each wepaon a pair of arms with different animations ?

north kiln
#

Is there a code question in there

subtle hedge
#

well yeah kinda

#

should i code in different animations for the arms and each and every gun

rich adder
#

group them by animation type, try to keep it generic?

eternal needle
subtle hedge
#

what about the reload animation ?

timber tide
#

skip the arms just use weapons as the arms

north kiln
#

Either way, there is not (or barely) a code question here and you should not be asking in this channel

subtle hedge
#

no code in the question, but i try to know how to aproach it for me to be easyer to code in the arms

north kiln
#

Just do what's the least amount of work for your game or authoring pipeline

subtle hedge
#

it's esential

waxen oracle
#

Is there a way i can use one script to change a variable from another script from a different object

slender nymph
chrome osprey
#

Guys can you help me!
I use Unity Netcode, the players can move and now I want to move the camera to the center of the players, does anyone have any idea how to do this

#

I would appreciate any attempt to help 😔

slender nymph
#

obligatory: use cinemachine

chrome osprey
earnest atlas
#

Can someone help. Its driving me crazy.

#
 public void ShowGameOverScreen(bool show)
 {
     SceneManager.LoadScene("2");
 }

Im pretty sure this is supposed to work. Considered from scene 0 to 1 it works. But from 1-2 no, 2-1 or 2-0 also no

polar acorn
earnest atlas
#

im loading by index arent i?

polar acorn
#

No

#

You're passing in a string

#

If you want to load by index, pass in a number

earnest atlas
#

wdy I am passing a number

polar acorn
earnest atlas
#

wait

polar acorn
#

"2" is a string

earnest atlas
#

Im tired as geck

#

btw does loading a scene resets it?

rich adder
#

yes, unless its a DDOL or static vars

earnest atlas
#

YAY I am almost done with this

waxen oracle
swift crag
#

I am unclear how you'd have a reference to the "script" of the instance

#

do you mean you have a reference to both a GameObject and to a monobehaviour class you've created?

waxen oracle
#

i have a reference to what says Image(Dialogue)

#

Image is the object

#

and dialogue is the script, the reference is to the script on that instance of image

earnest atlas
#

while I am here can I link these together?

If I anchor them to top right wont they overlap each other.

swift crag
polar acorn
waxen oracle
#

yeah i know

#

but how can i use the variables from that

wintry quarry
swift crag
#

ah, I was getting tripped up by the "Image" name

waxen oracle
#

nothing will happen, and at the bottom ill get an index error

wintry quarry
#

Show your code and your error

waxen oracle
#

IndexOutOfRangeException: Index was outside bounds of the array

polar acorn
waxen oracle
north kiln
#

Can you show the error

waxen oracle
#

the variable name script is working completely fine btw, thats attached to the same object

polar acorn
waxen oracle
polar acorn
#

Show the error

polar acorn
waxen oracle
#

That’s literally the error word for word

north kiln
polar acorn
#

The whole thing

#

including what line it's on

waxen oracle
#

Its not an error in the code

waxen oracle
#

its a red warning error i get after the codes ran

polar acorn
#

This is not a compile error your IDE could give you

waxen oracle
#

It shows in unity

north kiln
#

It's an exception, it has a stack trace

polar acorn
#

if you get that error, it's in your console

prime cobalt
#

Is it possible to make a bool be false while a specific animation in an animation controller is playing?

waxen oracle
#

Visual studio tells me i have 0 errors

polar acorn
#

it's in the Unity console because it's a runtime error in your code.

#

now show

#

the

#

error

swift crag
#

some kinds of errors can be caught by the compiler before your code runs

#

these are compile-time errors. you'll see them in both your code editor and in unity, and they'll stop your game from running

#

like if you make a typo or try to assign a value that doesn't fit into a variable

waxen oracle
#

IndexOutOfRangeException: Index was outside the bounds of the array.
dialogue+<TypeLine>d__8.MoveNext () (at Assets/scripts/ui/dialogue.cs:46)
UnityEngine.SetupCoroutine.InvokeMoveNext (System.Collections.IEnumerator enumerator, System.IntPtr returnValueAddress) (at <f7237cf7abef49bfbb552d7eb076e422>:0)
UnityEngine.MonoBehaviour:StartCoroutine(IEnumerator)
dialogue:startdialogue() (at Assets/scripts/ui/dialogue.cs:42)
dialogue:Start() (at Assets/scripts/ui/dialogue.cs:18)

summer stump
# waxen oracle Visual studio tells me i have 0 errors

The difference between compiler errors and runtime errors is important.
A compiler error means something in your code COULD NOT possibly work.
A runtime error is something that could work but for whatever reason failed when it tried

swift crag
#

other errors occur when the code runs

wintry quarry
swift crag
#

these are run-time errors

north kiln
#

dialogue.cs:46

polar acorn
#

Which has absolutely nothing to do with the code you've shown

waxen oracle
#

Because it shouldn’t

#

The variable i change never even appears in that code, its literally is just meant to show if it runs

polar acorn
waxen oracle
#

so that error is useless

#

and was just because nothings in there

polar acorn
north kiln
#

If you want anyone to help you, post the code that's relevant to the error that you want to solve

#

don't just post some random code that's got nothing to do with it

waxen oracle
#

The error would almost definitely be that theres nothing for it to run

polar acorn
waxen oracle
#

theres nothing for it to run because i cant give it anything to run because i do not know how

polar acorn
#

That's the entirety of the problem

polar acorn
#

Show the line of code

#

Your error literally says exactly what and why the problem is

waxen oracle
#

foreach (char i in lines[index].ToCharArray())

polar acorn
#

So how about show the actual !code

eternal falconBOT
polar acorn
#

instead of us having to basically beat the information out of you like lunch money

waxen oracle
#

i just stopped the error by adding 1 thing for it run, so it was because there was nothing in it

#

theres nothing in it because im trying to learn how to change variables from other objects

#

which is why i am here

summer stump
#

I'm kind of confused by the whole conversation. It feels like you don't really want help?
Why not provide what was asked for so many times?

north kiln
#

Certainly is an extremely frustrating conversation, where I'm considering just delivering a mute

waxen oracle
#

what would you mute me for 💀

#

!code

eternal falconBOT
swift crag
#

people do not enjoy having to play a game of 20 Questions

rich adder
#

learn how to use a coroutine

wintry quarry
#

Use coroutines.

waxen oracle
#
using System.Collections.Generic;
using UnityEngine;
using TMPro;
using System.Linq;

public class dialogue : MonoBehaviour
{
    public TMP_Text textcomp;
    public string[] lines;
    public float textspd;
    int index;
    public bool troo = false;
    // Start is called before the first frame update
    void Start()
    {
        textcomp.text = string.Empty;
        startdialogue();
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            if(textcomp.text == lines[index])
            {
                NextLine();
            }
            else
            {
                {
                    StopAllCoroutines();
                    textcomp.text = lines[index];
                }
            }
        }
    }
    void startdialogue()
    {
        index = 0;
        StartCoroutine(TypeLine());
    }
    IEnumerator TypeLine()
    {
        foreach (char i in lines[index].ToCharArray())
        {
            textcomp.text += i;
            yield return new WaitForSeconds(textspd);
        }
    }
    void NextLine()
    {
        if (index < lines.Length - 1)
        {
            index++;
            textcomp.text = string.Empty;
            StartCoroutine(TypeLine());
        }
        else
        {
            gameObject.SetActive(false);
        }
    }
}
north kiln
#

Not reading resources, not sending requested information, being randomly argumentative

waxen oracle
#

i argued where there was something they didn’t understand about the code

#

Because i didnt explain it fully

swift crag
#

you asked about a problem with X and then gradually revealed that it was actually Y

north kiln
#

!code please link to large codeblocks

eternal falconBOT
swift crag
#

a completely unrelated problem

waxen oracle
#

i only first noticed when i started this

polar acorn
north kiln
#

and then you didn't read the resource on stack traces I sent you twice, and started an argument about errors for no reason

swift crag
#

to bring us back to the original point: do you now understand how to modify a variable on another component?

waxen oracle
#

as the original problem says

#

the line of code
dia.troo = true:
is not doing anything

#

ill post the code again

polar acorn
summer stump
waxen oracle
#

so i can monitor if it changes

#
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;

public class camtext : MonoBehaviour
{
    public cammove script;
    public GameObject obj;
    public dialogue dia;
    // Start is called before the first frame update
    void Start()
    {
    
    }

    // Update is called once per frame
    void Update()
    {
        if (script.count == script.time)
        {
            obj.SetActive(true);
            dia.troo = true;
        }
    }
}```
polar acorn
waxen oracle
#

nothing is changing it back

#

and theres only 1 instance

north kiln
#

Have you checked whether that code is running

waxen oracle
#

Yeah, i have

#

the object is being set active, so its running

swift crag
#

then dia.troo is being set to true, end of story

north kiln
#

Can you check a bit harder, without any assumptions, by using the debugger or placing a log

swift crag
#

as long as something else is not activating whatever that object is

#

so yes, let's check this assumption

waxen oracle
#

okay

polar acorn
waxen oracle
#

after removing that line of code

#

the object does not activate

#

meaning that code 100% runs

polar acorn
#

Log dia.troo after you set it. See what it prints

north kiln
#

Request one thing, do something entirely different

#

wild stuff

waxen oracle
#

i checked

#

I got told to log it afterwards, wait a second

#

You just want me to use a regular debug log right?

north kiln
#

Preferably you would use the debugger, but I doubt you're going to

waxen oracle
#

i don’t know what that is

polar acorn
north kiln
waxen oracle
#

you confused me with see what it says mb

#

the debug log says that it works

polar acorn
waxen oracle
#

yeshhh
UnityEngine.Debug:Log (object)
camtext:Update () (at Assets/scripts/camera/camtext.cs:25)

polar acorn
waxen oracle
#

I did that

north kiln
#

Debug.Log($"{diag.troo} - {diag}", diag);

polar acorn
#

Log dia.troo after you set it. See what it prints

#

Don't just log a random word

#

Log something useful

#

Like I said twice

north kiln
swift crag
#

this will show you what you're actually referencing, which may not be what you expect

waxen oracle
#

True - Image (dialogue)
UnityEngine.Debug:Log (object,UnityEngine.Object)
camtext:Update () (at Assets/scripts/camera/camtext.cs:25)

polar acorn
north kiln
#

So it's set to true, and you can click on the log, look at the object it pings, and it should also be true

waxen oracle
#

how the fuck

polar acorn
#

It's a different instance isn't it

waxen oracle
#

Theres only 1

#

I understand that literally everything says its true except for the game which isn’t

polar acorn
north kiln
#

Can you show your setup

waxen oracle
#

Idk if thats my setup

#

idk what u mean by setup

polar acorn
waxen oracle
north kiln
#

Can you record a video of this happening

waxen oracle
#

tbh at this point i give up

#

im just gonna do it differently this is dumb

#

thanks for the help tho

north kiln
#

Either something else is setting it back to false, or you are. That's the only options here

polar acorn
north kiln
#

And the specific variable we're asking about being highlighted in blue really doesn't give me confidence that it's the code's problem

polar acorn
north kiln
#

Yeah, I don't know how you get that white border around a boolean, but if the label was selected the field wouldn't have an outline

earnest atlas
#

It was always correct XD

north kiln
#

Ah, it's the hover state

#

Selected the label then hovered? No idea, either way, video evidence of this happening would be required to go any further

vale sparrow
#

hey! does anyone know a way i can move an object from the scene inside a list, remove that object from the scene and still keep it in the list for later use

timber tide
#

prefab

vale sparrow
#

no work :(

#

either that or im using it wrong

#

i have a prefab saved in a variable which i reference to and add to the list before i delete the object. but the prefab gets deleted with it

north kiln
#

Show !code

eternal falconBOT
ivory bobcat
meager sentinel
#

Guys, i did the ide thing for VSC and i literally followed every step and the ide yet isn't configurated, what happens?

vale sparrow
# north kiln Show !code
if(Input.GetMouseButton(1))
        {
            var objectCheck = Physics2D.OverlapBox(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector3.one * 0.125f, 0, LayerMask.GetMask("Furniture"));
            if(objectCheck)
            {  
                gameManager.furnitureInventoryList.Add(objectCheck.gameObject.GetComponent<furnitureStats>().furniturePrefab);
                var listReference = gameManager.furniturePlacedList.Find(obj=>obj.name==objectCheck.gameObject.transform.GetComponent<SpriteRenderer>().name);
                gameManager.furniturePlacedList.Remove(listReference);
                Destroy(objectCheck.gameObject);
            }
        }
ivory bobcat
meager sentinel
#

yep

north kiln
ivory bobcat
vale sparrow
#

its messy as hell since this is my first time working with lists but what i want to do is when i right click, i "stash" a placed object by moving it from a list of placed objects to a list which serves as inventory that i can place again later

north kiln
#

doing things by name is a bad look, really should figure out how to make that same query by reference. Also, if you're just Finding to then remove, just call Remove with that same query?

queen adder
#

this function is called in update(). however, my crosshair image never disables itself !

#

i called debug.log() inside the condition where it disables my crosshair and it works

timber tide
#

what type is crosshair

queen adder
#

Panel

#

or Image in the script

tacit estuary
queen adder
#

yes

tacit estuary
ivory bobcat
queen adder
timber tide
#

panel is just a UI component with an image

#

you can hide the image

queen adder
#

see, the problem is

#

there are child images inside the parent panel

#

thats why i want to disable it entirely

north kiln
#

Then use a CanvasGroup to hide all the children

timber tide
#

does SetActive work, I forget

#

or does that break what you have too

north kiln
#

Also works of course, but depends on what you want and they have performance differences

queen adder
#

there is no defined setactive method inside a Image object

timber tide
#

SetActive on the gameobject

queen adder
#

oh

#

it works!

#

thank you Mao

jovial sandal
#

hey guys i am trying to make a inv systen but the drag and drop is not working i also have a hover bool to check if that is working and that isint working i have turned of raycast target on the drag/drop img does some1 know what is hapening(copied the code from the vid sorce bc i tought it was that but it aitnt)

queen adder
#

here is my revised code

timber tide
#

oh right yeah if you want to disable the children just disable the object

#

I read that wrong

north kiln
#

You're still reading directly from a Quaternion btw

meager sentinel
#

Idk what causes this, and i dont even know if it's a coding problem (if it's not, please lead me to the channel) when i shoot with my weapon it goes to the right, like this, the blue arrow represent to where the bullet goes

meager sentinel
ivory bobcat
meager sentinel
ivory bobcat
jovial sandal
queen adder
ivory bobcat
#

It isn't so much as rotating that's the problem but that you're using the z component of a quaternion, which isn't an Euler value.
#💻┃code-beginner message

queen adder
#

should i change my assigned object to this?

sturdy wren
#

how do i rotate the camera?

queen adder
timber tide
#

your other method would be fine too but you need to use those current euler values as well

queen adder
#

what was i going to ask

#

uhhh h

#

RIGHT

#

ok

#

how do i make objects have two layers at once?

#

i want the ground to be both grappleable and walkable(whatIsGround layermask)

north kiln
#

You can't

timber tide
#

tags probably

#

not unity tags for some reason

north kiln
#

Tag it as something specific and then add that to anything that the masks that look for grappable or walkable surfaces

timber tide
#

imagine if unity tags were bitwise enum

#

I'd probably use them

#

wouldn't even need to component search and instead just reference the gameobject tag when casting

jovial sandal
#

hey guys i am trying to make a inv systen but the drag and drop is not working i also have a hover bool to check if that is working and that isint working i have turned of raycast target on the drag/drop img does some1 know what is hapening(copied the code from the vid sorce bc i tought it was that but it aitnt)

dense root
#

Any idea why this code throwing an error when I try to add to the dictionary?

public Dictionary<string, string> language = new();
language.Add("apple", "ringo");
wintry quarry
#

it needs to go in a method

#

If you want to initialize the Dictionary inline you can do this:

public Dictionary<string, string> language = new() {
  {"apple", "ringo"}
};```
#

otherwise - use Awake:

void Awake() {
  language.Add("apple", "ringo");
}```
dense root
#

Ohhh

#

It needs to go in a method

wintry quarry
#

yes

prime cobalt
#

is there a way to set the base layer of an avatar controller's speed to zero while an avatar mask layer moves at full speed?

prime cobalt
#

I mean a way to control that speed in the code

meager sentinel
#

Someone may know why when i try to make PistolMesh active (it's not a mesh, it's a GameObject) it dont works, but somehow if you enable the object again (because it does disable on start) it also shoots, which is strange

dense root
#

How do I return a "random word" from dictionary?

    string GetRandomWord()
    {
        // Use Random.Range to get a random index within the list
        int randomIndex = Random.Range(0, JapEngDict.Count);

        // Get the word at the randomly chosen index
        string randomWord = JapEngDict[randomIndex];

        //  Remove the selected word from the list
        JapEngDict.RemoveAt(randomIndex);

        // Populate text if this condition is met.        
        if (JapEngDict.Count == 0)
        {
            inputField.placeholder.GetComponent<Text>().text = "No more words in the list!";
            Debug.Log(inputField.placeholder.GetComponent<Text>().text);

            textElement.text = textValue;

            return null;
        }

        // Return the selected word
        return randomWord;
    }
meager sentinel
#

Wait, maybe because it's unabled it can enable himself again?

#

I think so, am sorry for annoying

wintry quarry
#

Well... sounds pretty self explanatory - but show your quality and graphics settings windows

dense root
wintry quarry
#

scroll down - you'll have mixed assets

#

that one is a URP asset

#

what are the others

#

and what is the Graphics Settings set to

wintry quarry
gritty lion
#

My editor crashed without any errors

wintry quarry
#
        int randomIndex = Random.Range(0, JapEngDict.Count);

        // Get the word at the randomly chosen index
        string randomWord = JapEngDict[randomIndex];```
That thing just needs to be a list or an array, not a Dictionary
gritty lion
#

Is there any crash log to know what caused it?

dense root
wintry quarry
#

sorry not scroll down - but select all the different quality levels

wintry quarry
#

you could get an array of all the keys in the dict if you want

#

e.g.

string[] keys = JapEngDict.Keys.ToArray();```
dense root
#

Error CS0119 'ReadInput.JapSpaDict()' is a method, which is not valid in the given context

wintry quarry
#

what's JapSpaDict

#

like the error is saying, that's a method

#

you're trying to use a method like it's a variable

dense root
#

private void JapSpaDict() { Dictionary<string, string> JapEngDict = new Dictionary<string, string>(); JapEngDict.Add("apple", "りんご"); }

wintry quarry
#

yeah that's a method...

#

what are you doing

dense root
#

I'm trying to return a random word

#

From my dictionary

wintry quarry
#

What happened to JapEngDict

#

JapEngDict is your dictionary

wintry quarry
dense root
#

Sorry I changed the names

wintry quarry
#

it creates a new dictionary, adds something to it, and then you lose reference to it forever

dense root
#

What's the proper way to add a reference to it?

wintry quarry
#

you didn't just change names

#

assign it to a variable that exists outside the function

dense root
#

I'm trying to associate the Japanese word with the English

rich adder
dense root
#

Thank you

rich adder
#

you prob want that to be more flexible with params

wintry quarry
#

i have no idea why you have this function though - that's a weird function

#

what's the point of it

#

Is something else going to call it?

dense root
#

Here let me make a video

#

It might be easier if I just show you my game

wintry quarry
#

I don't think it would help to see the game

dense root
#

Okay

#

Nevermind

wintry quarry
#

Just an explanation of what the function is and what it's for and where it would be getting called and why it's called JapSpaDict

dense root
#

!code

eternal falconBOT
wintry quarry
# dense root

anyway back to this you would use your dictionary, which is called JapEngDict.

dense root
rich adder
#

ohh nvm you mean like a translate type thing?

dense root
#

yes

#

bingo

#

There are two boxes for the languages, one for Spanish, one for Japanese

rich adder
#

oh okay so how do you plan on filling this dictionary

dense root
#

I can manually type it I don't mind

#

The end goal is 100 words doesn't need to be anything fancy

#

Is Dictionary really the best data structrure for this?

rich adder
#

sounds like it, esp if you want 2 languages per word

dense root
#

Okay

rich adder
#

You can make 1 word as key and then custom struct/class as values, 1 string per language?

dense root
#

Okay let me try

wintry quarry
dense root
#

It is to key value pair the dictionary value

wintry quarry
#

Why?

dense root
#

i.e. apple -> りんご

wintry quarry
#

How is English involved in the game?

dense root
#

Well technically it's not but just for easier record keeping

wintry quarry
#

Sounds like you just want a mapping from the spanish word to the Japanese word

#

and/or vice versa

dense root
#

Yes

#

But I'd like to map it to English for reference

#
    string GetRandomWord()
    {        
        string[] keys = JapSpaDict.Keys.ToArray();
        
        // Use Random.Range to get a random index within the list
        int randomIndex = Random.Range(0, JapSpaDict.Count);

        // Get the word at the randomly chosen index
        string randomWord = JapSpaDict[randomIndex];

        //  Remove the selected word from the list
        JapSpaDict.RemoveAt(randomIndex);

        // Populate text if this condition is met.        
        if (JapSpaDict.Count == 0)
        {
            inputField.placeholder.GetComponent<Text>().text = "No more words in the list!";
            Debug.Log(inputField.placeholder.GetComponent<Text>().text);

            textElement.text = textValue;

            return null;
        }

        // Return the selected word
        return randomWord;
    }

How do I convert this from list previously to now the dictionary?

wintry quarry
#

Probably would do something like:

[Serializable]
public class Word {
  public string English;
  public string Spanish;
  public string Japanese;
}```

Then you'd have :
```cs
public Word[] allWords;
Dictionary<string, Word> mappings = new();

void Awake() {
  foreach (Word word in allWords) {
    mappings[word.English] = word;
    mappings[word.Spanish] = word;
    mappings[word.Japanese] = word;
  }
}```
#

then you have a map from all the languages to each other @dense root

#

and you just fill the words in the inspector

#

and:

Word GetRandomWord() {
  return allWords[Random.Range(0, allWords.Length)];
}```
rich adder
#

nice 😛 i was doing exactly similiar

dense root
#

Getting an error :(

#

ohhh

#

capitalization lol

wintry quarry
dense root
#

Getting this unusual error

#

About ambiguity

wintry quarry
#

it will go away

#

it's because you have using System; and using UnityEngine; and they both have a Random class

rich adder
#

another solution can be to write using Random = UnityEngine.Random

#

this tells the computer you want only Random from that namespace when using it

timber tide
#

just noticed the other day vs was adding namespaces even if they were conflicting with my other namespaces

rich adder
#

VS weird sometimes xD

#

Love when it randomly adds VisualScripting namespace

dense root
#

How do I return a string from my GetRandomWord method?

timber tide
#

ive had that happen too idk where from

dense root
timber tide
#

I think it doesn't remove the namespace from the undo history if you accidently add the wrong class call

rich adder
#

the string is inside

wintry quarry
#

yours is different

dense root
#

Oh stupid me lol

#

So how do I convert from Word to String?

rich adder
#

access the specific word with .

dense root
#

Ohhh nice

wintry quarry
dense root
#

How do I add words?

wintry quarry
dense root
#

ohh

prime cobalt
#

I asked in animation chat but it kinda applies here too, is there a way to do something like this? (Enemyloco is an animation controller and this specific function is read only)

#

I only want to change the speed of a single state or layer not the whole controller

wintry quarry
#

Then in the state you can do this:

prime cobalt
#

Oh sweet ok thanks

dense root
#

I'm getting a null reference error.. any ideas?

north kiln
#

Surely you can figure this out

dense root
#

lol Let me keep trying at it, I've tried all the options in the inspector

north kiln
#

What's the inspector got to do with it

dense root
#

Isn't it asking me to select the Text Element in the inspector?

#

To reference it to the code?

north kiln
#

It's not asking you to do anything

#

what are you trying to access on the line of code that's throwing the NRE

dense root
#

I'm trying to access InputField

north kiln
#

No

wintry quarry
dense root
#

Japanese

wintry quarry
dense root
#

To the left

wintry quarry
#

I mean in the hierarchy

dense root
#

Above Spanish

wintry quarry
#

What's it called?

dense root
wintry quarry
#

Ok and look at your code

#

Your code is looking for something called what?

dense root
#

It's looking for InputField(Legacy)

wintry quarry
#

Yep

dense root
#

oh

north kiln
polar acorn
proud robin
#

how do i know what values to put for cycles offset 😇

dense root
pallid heron
#

I have never figured out how to get vscode to put opening brackets on the same line

dense root
#

inputField = GameObject.Find("Japanese").GetComponent<InputField>();

polar acorn
#

The one you're looking for in code

dense root
#

Japanese was previously named that

#

But I renamed it to distiniguish it

polar acorn
#

So, follow up question:
Why are you using Find at all

Just make a public InputField variable and drag it in

dense root
#

I could try that

#

How do I convert this to use a word as defined before?
japInputField.placeholder.GetComponent<Text>().text = newPlaceholderText;

#

This is how the inspector looks now

north kiln
north kiln
dense root
#

I assigned my Inputfield in the inspector I'm not sure what's creating the NRE

north kiln
#

the one in your screenshot has nothing to do with an input field

dense root
#

oh...

#

I got it! Thank you everyone

normal mango
#

trying to call the "StopPlacement" method from the "PlacementSystem" script to use in the "CameraPosition" script, whats the correct way of doing this?

north kiln
#
public PlacementSystem Whatever;

void Start() {
  Whatever.StopPlacement();
}
normal mango
#

what is whatever supposed to be?

north kiln
#

it's a name, call it whatever the hell you want

normal mango
#

ah ok

polar acorn
normal mango
#

No it's PlacementSystem that has the function, but vertx's code worked

shell herald
#

i am currently working on a 2d platformer gun aim system. it aims where the cursor is pointing, which works great, however im struggling to try to limit the rotation (limit the gun from going over 180 degrees so that it doesnt look weird when its pointing to another direction than my character)

I tried to do it with (as you can see in the bin) " difference.x = Mathf.Abs(difference.x);"
which works great if the player faces right, but doesnt work when the player faces left

how would i go about fixing this?

https://hastebin.com/share/buzavegojo.csharp

vernal plume
vale sparrow
shell herald
queen adder
#

when you double click the message in the console

gaunt ice
#

the method right before (lower then) the top one(log) ?

timber tide
ionic lava
#

Hello, anyone here that could help me with a very basic jump animation in 2D game? I've set up the animations for walking and idle properly and succesfull. But for some reason my Jump animation gets looped when mid air, despite the fact I unchecked "Loop Time"

queen adder
rich adder
ionic lava
rich adder
queen adder
supple wasp
#

I need help with this, it tells me here that the text does not exist in the current text, how can I fix it? is to turn shadows on and off using a toggle

rich adder
supple wasp
eternal needle
#

another win for chatgpt, giving you code that doesnt even compile

#

if you really cannot solve the issue of "does not exist in current context", drop what you are doing and go do some basics of c#.

polar acorn
#

How about asking ChatGPT to write code that exists

eternal needle
#

My absolute favorite from chatgpt was the Color.Distance incident someone had

eternal needle
charred spoke
eternal needle
eternal needle
charred spoke
#

Not mine haha

#

I called it distance rather than difference simply to be the same as a Vector3

#

Now Im sitting here thinking what the cross product of two colors look like

nova swift
# rocky canyon moving platforms are always a PITA

Hey, you've probably forgotten about the whole issue I was having, but I thought you could find this interesting or helpful. I managed to fix the problem.
Previously I was just updating the player's rigidbody positions, which was great physics wise, but caused terrible stuttering visually.
I tried moving just the transform, and there was no stuttering, but the physics became all janky. So i tried moving the rigidbody positions first, then the transform along with it, and it fixed the stuttering somehow. Also needed to round the player's offset on the platform to the nearest 1/32 for a pixel perfect camera, otherwise stuttering would continue:

                float roundedOffsetX = Mathf.Round(offsetX / 0.03125f) * 0.03125f;
                playerScript.rb.position = transform.position + new Vector3(roundedOffsetX, 1);
                playerScript.transform.position = transform.position + new Vector3(roundedOffsetX, 1);
                playerScript.sprite.position = transform.position + new Vector3(roundedOffsetX, 1.25f);

oh and also had to change interpolation mode to none

eternal needle
# charred spoke Now Im sitting here thinking what the cross product of two colors look like

assuming non zero values (and alpha always 1), i think it would just be like applying an offset in that circle you can use to set colors in inspector. Like green * white = red, red * white = blue, blue * white = green. When reversing the order, basically just go in the reverse way around the circle. white * green = blue etc
If using like fractions (not fully green) then idk lol but its probably similar just more dim

charred spoke
#

Would be a interesting experiment haha

#

One can probably make a whole indie game where colors and directions are the same thing haha

crystal sierra
#

I have a question.
Is it possible to create a custom editor script so that I can drag a prefab into a list of sprites (sprite[]) in the inspector, loading all the frames from that prefab?

eternal needle
# charred spoke Would be a interesting experiment haha

i was experimenting with more decimals values in it, id say itd be pretty hard to design a game with it lol. Im not the best at visualizing cross products in 3d, but the offset thing I said is basically what happens if you use a pure white value for one color. When one color isnt pure white, it'll start to kinda fade between black and an offset color

crystal sierra
eternal needle
crystal sierra
#

Yes

#

The prefab is an imported .asseprite file

crystal sierra
eternal needle
#

also yea I dont know much about that file type sorry

crystal sierra
#

Thanks for your help though

#

It's all g

verbal dome
#

@crystal sierra You can ask in #↕️┃editor-extensions but like bawsi said, EditorGUILayout.ObjectField for the prefab and a button would be easiest

crystal sierra
#

Thanks. I'll try that

nimble scaffold
#

Guys I have a serious problem..... In my car game... The speed of my car is much and it's acceleration also but in rigidbody 's info section the speed showing is something in 0. Something... Why?? But in game speed is much... And in speedometer script I converterted m/s (SI Unit) to km/hr..

slender nymph
#

show relevant !code

eternal falconBOT
desert elm
#

is there a way to increase the resolution of the game?

#

other than
scaling everything up?

nimble scaffold
# nimble scaffold Guys I have a serious problem..... In my car game... The speed of my car is much...
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Speedometer : MonoBehaviour
{
    public Rigidbody target;

    public float maxSpeed = 0.0f; // The maximum speed of the target ** IN M/S **

    public float minSpeedArrowAngle;
    public float maxSpeedArrowAngle;

    [Header("UI")]
    public Text speedLabel; // The label that displays the speed;
    public RectTransform arrow; // The arrow in the speedometer

    private float speed = 0.0f;
    private void Update()
    {
        // The speed is now the magnitude of the velocity in meters per second.
        speed = target.velocity.magnitude;

        if (speedLabel != null)
            speedLabel.text = ((int)speed) + " m/s";
        if (arrow != null)
            arrow.localEulerAngles =
                new Vector3(0, 0, Mathf.Lerp(minSpeedArrowAngle, maxSpeedArrowAngle, speed / maxSpeed));
    }
}

@slender nymph the code

slender nymph
#

now show how you move it

nimble scaffold
#

By wasd keys

slender nymph
#

jesus christ, i obviously meant the code

nimble scaffold
#

Oh

slender nymph
#

you seem to have already forgotten how to correctly share !code
but the issue is that you are moving via the transform. that does not change the rigidbody's velocity

eternal falconBOT
nimble scaffold
#

using UnityEngine;

public class SimpleCarController : MonoBehaviour
{
    public float initialAcceleration = 10f;
    public float accelerationIncreaseRate = 5f;
    public float steeringSpeed = 5f;
    public float brakePower = 20f;
    public float inertiaFactor = 0.95f;

    private float currentAcceleration = 0f;
    private float currentSteering = 0f;

    void Update()
    {
        // Acceleration
        if (Input.GetKey(KeyCode.W))
        {
            currentAcceleration += Time.deltaTime * accelerationIncreaseRate;
        }
        else
        {
            currentAcceleration *= inertiaFactor;
        }

        // Steering
        currentSteering = Input.GetAxis("Horizontal") * steeringSpeed;

        // Braking
        if (Input.GetKey(KeyCode.S))
        {
            currentAcceleration -= Time.deltaTime * brakePower;
        }

        // Move the car
        transform.Translate(Vector3.forward * currentAcceleration * Time.deltaTime);
        transform.Rotate(Vector3.up * currentSteering * Time.deltaTime);
    }
}

nimble scaffold
slender nymph
#

move using the rigidbody instead of the transform

#

or pass the speed and direction from this component to the speedometer component. but if you want to move it via the transform why does it even have a rigidbody

nimble scaffold
queen adder
#

Is it true that there was an era where unity devs dont have UI objects and must do UI stuff via purely GUI?

tender hound
#

what is the best way in a 3d world to find a path? is it navmesh or do i have something else?

slender nymph
#

navmesh is unity's built in way. otherwise you could get some asset or implement your preferred pathfinding algorithm manually

left gazelle
#

hello

#

is there any help section in this server?

slender nymph
#

!support

eternal falconBOT
#
Where can I get help?

Take a look at #🔎┃find-a-channel

:warning: This is not a channel for official support.

Please do not ping admins, moderators, or staff with Unity issues.

fickle plume
left gazelle
#

ok thanks

queen adder
#

As we know, the List<T>'s array size increases by doubling the starting point of capacity 4,8,16,32,64... based on the count. How does it work if i pass Initial Capacity? Lets say i said "100" at the capacity at initialization of new list. Will it double to 200 or snap to the 128?

keen dew
sleek notch
#

Collision doesn't work often. When I'm shooting from starting position it works fine but if I move torward to wall or rotate tank about 90 degrees it doesn't work

brisk escarp
#

if anyone is free i have a slight problem with my code, (context: im learning how to do 3d movement in unity and i am having issues with line 34 heres the code)
(and heres the error Assets\Scripts\Playermovement.cs(34,70): error CS0131: The left-hand side of an assignment must be a variable, property or indexer )

#

Fixed it dont worry

queen adder
#

!ide @brisk escarp

eternal falconBOT
queen adder
#

Helps you detect them later on

brisk escarp
#

thanks, had that on my old laptop and forgot to add it to my new pc.

sleek notch
languid spire
slate gale
#

Use tags instead

sleek notch
#

You have video of that under thta

#

that

slate gale
#

What

dry tendon
#

I need help, the next code it's supposted to save another boxhelp height on boxHelpHeight var, that works correctly, cause the log shows me the values changing... But when i try to apply the var's value to the right boxhelp it doesn't work... What could happen? The right boxhelp changes it's vertical size to a really small one and it doesn't do nothing with that code```csharp
boxHelpHeight = GUILayoutUtility.GetLastRect().height;
Debug.Log("BoxHelp Height: " + boxHelpHeight);

// RIGHT BOXHELP
EditorGUILayout.BeginVertical(EditorStyles.helpBox, GUILayout.Height(boxHelpHeight), GUILayout.Width(EditorGUIUtility.currentViewWidth * 0.25f));

GUILayout.Space(2);
GUI.backgroundColor = new Color(46f / 255f, 204f / 255f, 113f / 255f);
propertyAdditionMenu.Draw();
GUILayout.Space(15);
GUI.backgroundColor = Color.white;

EditorGUILayout.EndVertical();```

sleek notch
slate gale
#

Is your wall a plane or cube

ivory bobcat
slate gale
#

Do you use a plane or box mesh for your wall?

dry tendon
north kiln
#

I presume they're using HDRP and that's a planar reflection probe

slate gale
# dry tendon

Maybe no one knows. Ask chat gpt maybe it can find a bug

#

Check the assetstore

autumn arrow
#

nohing good there

slate gale
#

Too bad

autumn arrow
#

its for school project im not wiling to pay

slate gale
#

Maybe just make it yourself??

#

Then you’ll actually learn something

#

For you know

autumn arrow
#

i made it but it horible

slate gale
#

School

autumn arrow
#

and broken

slate gale
#

The place where you’re supposed to learn

#

Instead of cheat and copy

dry tendon
slate gale
#

Then idk sorry, not too experienced myself with editor scripting 🙁

north kiln
#

@autumn arrow don't cross-post

dry tendon
north kiln
#

If you have a specific question, ask it, instead of asking something so general and requiring people invest in a conversation with possibly no ends

north kiln
#

no

languid spire
dry tendon
languid spire
#

one of the reasons I stopped using IMGUI was because expecting it to behave rationally is unrealistic especially in edge cases

stable ore
#

i followd a tutorial double checked it twice

#

and my animation is still bugged

#

when i move the movement animation and jumping is at same time

dry tendon
north kiln
languid spire
stable ore
#

somebody

languid spire
# stable ore plz help

really? On the basis of your question and the code you incorrectly posted an answer is impossible

stable ore
#

this the other half

languid spire
#

!code

eternal falconBOT
dry tendon
stable ore
#

there is no errors in it i tried debugging

dry tendon
languid spire
stable ore
#

why is it red with no errors

swift crag
#

do you see this up top? if so, hit the red button to stop

supple night
#

can anyone offer tutoring in beginning development in Unity or UE?

swift crag
#

!learn

eternal falconBOT
#

:teacher: Unity Learn ↗

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

stable ore
# supple night can anyone offer tutoring in beginning development in Unity or UE?

In this part, we will take care that our player can only jump while he is standing on the ground.

Github repository:
https://github.com/codinginflow/2DPlatformerBeginner


🎓 Learn how to build a 2D game in Unity (beginner): https://www.youtube.com/playlist?list=PLrnPJCHvNZuCVTz6lvhR81nnaf1a-b67U
🎓 Learn how to build a 3D gam...

▶ Play video
#

folllow dis tutorial from episode 1

#

it really helped me understand basics

supple night
stable ore
stable ore
supple night
#

Okay you made it farther than I did with the Domestika tutorial im referring to

#

I trust you Batman

stable ore
#

if you want

#

or you can watch the video i sent

#

thats where im at towards the end

dark oak
#

I need help!!!
How can i install c sharp on windows 7?

or enable c sharp snippet on vs code

eternal falconBOT
#
Visual Studio Code guide

If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:

https://on.unity.com/vscode

rich adder
#

you also need to prob download .NET sdk

gusty sorrel
#

i have three 2d rigidbodies(fuel tank, engine base/mount and the engine bell) each is connected with a fixed joint to the one above it. pressing a/d should rotate the engine while the base does not move. what really happens is the engine base rotates, while the bell stays in the same rotation(relative to the base). any ideas why this happens?

#

i'll copy the code i use

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

public class Controls : MonoBehaviour
{
    public float throttle, thrust, rot, gimbal;
    public Rigidbody2D rb, mrb, trb;
    public GameObject mount, tank;

    void Start()
    {
        throttle = 0f;
        thrust = 170f;
        mount = GameObject.Find("Engine Base");
        tank = GameObject.Find("Fuel Tank");
        mrb = mount.GetComponent<Rigidbody2D>();
        trb = tank.GetComponent<Rigidbody2D>();
        rb = GetComponent<Rigidbody2D>();
    }

    
    void Update()
    {
        
    }

    void FixedUpdate()
    {
        if (Input.GetKey(KeyCode.LeftShift))
            throttle += Time.fixedDeltaTime;
        if (Input.GetKey(KeyCode.LeftControl))
            throttle -= Time.fixedDeltaTime;
        if (Input.GetKey("z"))
            throttle = 1f;
        if (Input.GetKey("x"))
            throttle = 0f;

        mrb.rotation = trb.rotation;
        rot = mrb.rotation;
        if (Input.GetKey("a"))
            gimbal = -15f;
        else if (Input.GetKey("d"))
            gimbal = 15f;
        else
            gimbal = 0f;
        rb.rotation = Mathf.Lerp(rot, rot + gimbal, Time.fixedDeltaTime*10);

        throttle = Mathf.Clamp(throttle, 0f, 1f);
        rb.AddForce(thrust * throttle * transform.up);
    }
}
languid spire
gusty sorrel
#

why?

languid spire
#

because it will not work correctly

gusty sorrel
#

its been working correctly so far

languid spire
#

notice how you've had to use GetKey?

vagrant shard
#

I am currently working on a Unity project that involves multiplayer functionality using NGO (Netcode for GameObjects). I am facing challenges in synchronizing bullets between the server and clients.

Specifically, I am encountering issues with ensuring that when a player shoots a bullet, its position, and other relevant information are synchronized correctly across the network for all players.

If anyone has experience or insights into properly synchronizing bullets in a Unity multiplayer environment, especially using NGO, I would greatly appreciate your guidance or any code snippets that could help me troubleshoot and resolve this issue.

gusty sorrel
languid spire
#

GetKey fires for each frame the key is held down

gusty sorrel
#

what should i use then?

languid spire
#

GetKeyDown in Update would be favourite

gusty sorrel
#

i cant do getkeydown with throttle controls

#

anyway i dont think input has anything to do with the wrong object being rotated

swift crag
#

that's going to rotate whatever object that rigidbody is attached to

gusty sorrel
#

and its attached to the engine bell

swift crag
#

how is the engine bell connected to the rest of the ship?

#

note that parenting rigidbodies to each other can cause unexpected behavior

gusty sorrel
#

no parenting

#

only joints

swift crag
#

ah, okay, good

gusty sorrel
#

engine bell -> engine mount -> fuel tank

swift crag
#

Is the ship a lot more massive than the engine bell?

#

and how is the bell jointed to the ship?

gusty sorrel
#

fuel tank has a mass of 10, engine has 1

swift crag
#

if the joint doesn't permit free rotation, and you change the rotation of the bell, the entire ship will have to rotate

#

I haven't done a lot with joints, so I'm not sure what the "correct" way to do this would be

gusty sorrel
swift crag
#

A fixed joint forces two rigidbodies to maintain the same relative position and rotation

#

You either need a different kind of joint, or you need to update the rotation the joint is trying to maintain

gusty sorrel
#

there was some funny wobble going on between the fuel tank and the engine base so in the script i set the rotation of the base the same as the rotation of the fuel tank and then rotated the bell relative to the base

swift crag
#

I use joints a little, but I'm not quite experienced enough to know what the best option is here

gusty sorrel
#

i tried going for a hinge joint but i couldnt figure out how to set the angle in the code so the engine was just flapping around freely when turned on

#

relative joint fixed the issue

#

yay

stuck palm
#

are scriptable objects ddol?

#

i wanted to make scriptable objects as a way to save level data, but idk if that would work

queen adder
#

SO's exist in project folder

#

they can kinda hold their data yes, but they will get reset per restart of the game (closing and reopening)

stuck palm
#

thats fine

#

i can implement a save system then

#

i was just thinking an SO would make sense because levels all hold the same data, such as like time and stuff

queen adder
#

just try it for now, last time i tested, I used SO's to send data from 1 scene to another and that worked

#

I did use an Instantiated(so) btw, and they were referenced by a singleton ddol

#

not really sure if that was the reason the data persisted

swift crag
#

A ScriptableObject, like any other Object, will be unloaded some point after all references are lost

#

If Scene A references an object and Scene B doesn't, and all other references are lost, then the object unloads if you load Scene B in single mode

swift crag
stuck palm
#

What is this singleton business i keep hearing about

queen adder
#

yea quite had to clarify that cause i doubted their case will be the same as mine before

swift crag
swift crag
#

classically, you'll make an instance and stick it in a static field

#

I store some runtime data in scriptable objects for my settings system

stuck palm
#

in what class would u make that in?

swift crag
#

I load an object that references all other settings objects, either directly or indirectly, when the game starts

#

so all of the objects stay alive forever

queen adder
#

arent you familiar with singletons yet?

#

in this case, you better make a new class

#

sticking it to another calss will just make that class messy

swift crag
#

You should create a serializable class that holds all of the data you need

#

and then use something like Json.NET to serialize and deserialize that class

#
[System.Serializable]
public class LevelStats {
  public float completionTime;
  public float score;
}
#

for example

queen adder
#

We can serialize SO's though, cant we?

#

I remember grabbing a tool before that can do so

swift crag
#

Not without some extra legwork, at least

#

You're not supposed to directly construct ScriptableObject instances

#

and naïvely trying to serialize and deserialize them would mean you're constructing a new instance

queen adder
#

i remember that tool just place the values in an existing SO instance

tough lagoon
#

I'm just going to say i completely agree with Fen, to me, its trying to fit a round peg in a square hole

stuck palm
#

i think im just gonna leave level data alone for a while

queen adder
#

you feed it string and an instance of an SO

stuck palm
#

im nowhere near that point yet i was just wondering if it was possible

swift crag
#

You should distinguish unity serialization from your own serialization

#

An object is serializable by Unity if the game engine can understand how to turn it into data and then get the original object back

#

A good example of the difference: dictionaries

stuck palm
#

so i might just do that again

swift crag
#

Json.NET can handle dictionaries just fine

#

(and with a little finagling, you can even do dictionaries with complex key types)

#

Unity has no clue what to do with a dictionary

swift crag
#

they're serialized, and you make files (assets) out of them

#

but you don't create and store new ones at runtime

queen adder
#

anyway```cs

public static T Circle_GetOneComponent<T>(Vector3 position, float Radius, int layermask = -5)
    => Physics2D
    .OverlapCircleAll(position, Radius, layermask)
    .Select(x => x.GetComponent<T>())
    .FirstOrDefault();```why is one Overlap hitting and the other doesnt? ![UnityChanOops](https://cdn.discordapp.com/emojis/885169594879328306.webp?size=128 "UnityChanOops")
swift crag
#

maybe it's just on the edge

#

i don't know how well the visual lines up with the actual physics query

fringe kindle
#

How do I reset a scene upon death but keep the lives reduced instead of resetting?

tough lagoon
swift crag
#

one option: use DontDestroyOnLoad to move an object into a special scene that never unloads

#

another option: make the lives counter static, so that it's not tied to a specific object

swift crag
#

and for settings, the actual data lives in them to

#

(configurations aren't global settings; they're for customizing specific things)

#

so their data actually lives elsewhere

#

but when serializing, I pull that data out and create a plain old C# object that gets serialized

queen adder
swift crag
#

Looks different to me. Compare where the circle touches the building

swift crag
stuck palm
swift crag
#

that's an anonymous function

#

oh wait no it's not

queen adder
#

rotation? wait im iliterate lol

swift crag
#

it would be if it looked like this

#
var wat = (x) => x * 2;
#

That's just an expression-bodied member

stuck palm
#

does the arrow replace the brackets or

swift crag
#

an expression-bodied method, specifically

#

It lets you write a method as a single expression

queen adder
#

ah yeas

swift crag
#

So yeah, it's an alternative to writing a method made up of many statements

#

You can also make expression-bodied properties

queen adder
#

it's called expression body

swift crag
#
public int Property => 3;
public int Method() => 3;
#

I like mixing this with switch expressions!

stuck palm
#

what is this event system that keeps showing up in my hierarchy

swift crag
#
public int PlayerCount => mode switch {
  GameMode.SinglePlayer => 1,
  GameMode.Duel => 2,
  GameMode.FortniteGaming => 100
};
swift crag
stuck palm
#

oh right

swift crag
#

it tells buttons when they're getting clicked and keeps track of the currently selected game object

stuck palm
#

i havent done anaything with that yet but i feel like i'll have to soon

#

cus im using controllers

swift crag
#
public int PlayerCount => currentMode.playerCount;
swift crag
#

notably, it's really easy to just...deselect

#

and then be trapped forever

stuck palm
#

thats great

swift crag
#

a common fix is to have a component whose job is to just select something

#
void Update() {
  if (!EventSystem.current.currentSelectedGameObject) {
    var target = FindFirstObjectByType<Selectable>();
    EventSystem.current.currentSelectedGameObject = target;
  }
}
#

I do things more granularly, but the same idea holds

#

each of my menu screens knows if it's the "active" one and is responsible for selecting something if necessary

#

hey Fen! what if you have two active menu screens that both need to be usable at the same time?

🫠

#

i should think about that

swift crag
#

you see two things highlighted at once

#

I've played around with auto-selecting whatever is under the cursor, but that can be unintuitive if you're using the keyboard to adjust sliders while clicking around menus

stuck palm
tough lagoon
swift crag
#

I was originally deserializing directly into the type that actually holds the runtime data, but then I realized I'd have to replace the existing instance with a new one

#

which was a hassle because I'd have to copy over some other information (like lists of listeners for each config item)