#💻┃code-beginner

1 messages · Page 495 of 1

wintry quarry
#

you'll need an if statement

spiral narwhal
#

Big Unity L

wintry quarry
#

yeah

spiral narwhal
#

But thanks :)

ruby python
#

Brain fart moment. I've got a raycast going from the camera. Is it possible for it to trigger a method just once when it hits the thing I'm looking for, and also, to trigger another method just once, when there is no 'hit' ? 😕

wintry quarry
#

it will only do things once unless you write a loop

#

or if you run the code multiple times

#

for example if you put something in Update, that happens every frame

ruby python
wintry quarry
#

Ok then you just need to track what you're looking at

#

and only do the thing you want when you first start looking at something new

#

it all depends how you want this thing to behave

rough orbit
#

Anyone know why VisualStudio keeps spamming me that TextMeshProUGUI could not be found? Also namespace name UI does not exist in the namespace UnityEngine? My game still works, so no compiler errors, but I'm afraid to save and push to github if this is gonna bite me later. Only thing I know I've done is switching between windows build and web build. Prior to that there were no errors in the scripts.

burnt vapor
eternal falconBOT
rough orbit
#

TMPPro is available in the hierarchy if I want to create a new gameobject

wintry quarry
drowsy oriole
#

Hi I'm still having problems with this script, I refuses to disable, and now It won't ENable so I don't know what to do, I just started doing code again, so don't judge me https://hastebin.com/share/cegekoluwa.csharp

rich adder
rough orbit
rough orbit
ruby python
#

Okay, quick and dirty explanation, I'm using Feel from MoreMountains a lot in my current project. The thing I'm trying to do at the moment is......
When the raycast hits a certain type of object, it triggers a Feel controller that simply increases the Weight of an IK rig attached to the players arm from 0-1, 'raising' the arm so that it points at the raycast 'hit'. This funcionality I have working great, I have the arm raising up etc. The issue I'm having is the opposite action (Arm lowering/weight animating back to 0). The Feel Controller is all correct etc. It's my if(raycast....blah blah} else {lowerarmstuff] that's bugging me. lol.

    void Update()
    {
        RaycastHit hit;
        if (Physics.Raycast(playerCamera.transform.position, playerCamera.transform.forward, out hit, maxRaycastDistance, interactableLayerMask))
        {
            if (hit.transform.gameObject.CompareTag("Ore"))
            {
                Debug.Log("Arm Should Deploy Here");
                shoulderObject.LookAt(hit.point);

                if (!armRaised)
                {
                    Invoke("ArmRaise", 0f);
                }
            }
        }
        else
        {
            Invoke("ArmLower", 0);
        }
    }

Sorry if it's too long, but that's what I have so far (I thought Invoke would be the solution, but after looking at it and thinking about it, I realised I'm an idiot. lol.)

rough orbit
rich adder
# rough orbit How to do that?

close VS there should be a button inside External Tools in Preferences in unity, click it then open script from unity again

drowsy oriole
#

It is a button script, when pressed it (is supposed to) calls Enable() but now it doesn't and I dont know why

rich adder
rough orbit
drowsy oriole
#

So if I remove it, then it gets enabled but won't disable

rich adder
#

check the stacktrace and see who's calling it

rough orbit
# rich adder nope

Doesn't seem to have helped. Then again nothing seems to happen when I click regen project files. The button gets clicked but nothing happens

drowsy oriole
#

yes, RIGHT after Enabled() is called

wintry quarry
verbal dome
rich adder
#

curious to see whats happening there

ruby python
rich adder
#

oh thats weird

rough orbit
wintry quarry
rich adder
# rough orbit

I wonder if its only loading the main assembly and not the external package ones.. def try going through the steps again for VS config.
if you expand References under Assemblies, I wonder if you find the UI one there (prob not)

wintry quarry
#

Also why are you invoking it instead of just calling it

ruby python
verbal dome
wintry quarry
#

yeah that's an excellent point^ you're missing a whole branch of the logic tree

#

I think the cleanest formulation here would be like:

bool hitOre = false;
if (Raycast(...)) {
  if (hit.COmpareTag("Ore")) hitOre = true;
}

if (hitOre && !armRaised) ArmRaise();
else if (!hitOre && armRaised) ArmLower();```
#

(pseudocode to show the logical structure)

ruby python
#

Okay, I got it working. (probably terrible implementation, but for the moment it works, so I'm happy. lol.)

        RaycastHit hit;
        if (Physics.Raycast(playerCamera.transform.position, playerCamera.transform.forward, out hit, maxRaycastDistance, interactableLayerMask))
        {
            if (hit.transform.gameObject.CompareTag("Ore"))
            {
                Debug.Log("Arm Should Deploy Here");
                shoulderObject.LookAt(hit.point);
                if (!armRaised)
                {
                    ArmRaise();
                }
            }
            else
            {
                if (armRaised)
                {
                    ArmLower();
                }
            }
        }
wintry quarry
ruby python
#

With all the things I'd tried, one small detail I missed. I forgot to add the 'terrain' layerMask.

And I don't think so. If it's not looking at 'ore' specfically the ik rig is set to 0 and the player is completely goverened by animations.

rough orbit
#

Does it ever happen that VS configs get scewed up when switching builds?

#

I've always been in the windows build and never had this issue before, then I switched to web and got the errors, switched back to windows and it's there now too. The game works though, no error messages in Unity, it's only VS that give me this.

rich adder
# rough orbit

yeah you see the ones missing have exclamation mark for some reason VS is not detecting them

#

the ones in UnityEditor work fine for some reason

ruby python
wintry quarry
#

then you can detect any interactable thing including things that are not ores

ruby python
#

All my current interactables are using that method. 🙂

harsh wadi
#

Sorry to ask again but do you have any solution regarding to my problem about jumping less when i jump on the edge of a platform? @wintry quarry

ruby python
#

Current State of what I have 🙂

steep rose
#

Neat

ruby python
#

Honestly, that Interactable script you shared a while ago is suuuuuuuch a time saver. lol.

steep rose
#

Did you provide code in the question?

harsh wadi
#

@steep rose here and we discussed a bit about it

nocturne kayak
#

Hey

#

I think i don't understand how Vector3.Project's supposed to work

steep rose
#

Then use docs

#

They will tell you how it works

nocturne kayak
#

Yeah well

steep rose
#

!docs

eternal falconBOT
nocturne kayak
#

Let me show you what happened

steep rose
#

Okaaay.. and what is this?

nocturne kayak
#

It's not supposed to snap to world 0 when i do that, might have something to do with it converting localPosition to world Position? but i'm not sure

nocturne kayak
#

This would be the desired result

#

The problem is that, well, this one isn't locked to a single axis

#

This is the script, the only difference between those two videos is that at like 54 in the script, first video is ' transform.position = Vector3.Project(hitPoint, transform.up);'

hollow slate
nocturne kayak
#

second is transform.position = hitPoint;

hollow slate
#

yeah they do project it.

#

You can take the code as it is (probably) and in the end make sure that the position is Vector3.Project(whatever you're grabbing, The axis is must follow)

#

oh, nevermind

#

I see your issu enow

#

issue now*

#

you want it to follow a plane yes @nocturne kayak ?

#

There's a function called Vector3.ProjectOnPlane. In your case, you'd use transform.up to define the normal of this plane. Vector3.Project projects only onto a single axis, not a plane.

#

that should achieve the desired result.

nocturne kayak
#

Oh, i want it to be projected on a single axis

hollow slate
#

oh.

nocturne kayak
#

I didn't use projectonPlane, but it is already snapping to a virtual plane i created

hollow slate
#

so what's the issue exactly?

nocturne kayak
#

The desired result would be having it slide along green line, not red

hollow slate
#

aha, I see what's happening now

#

the projecting works in world space. You must add the cube's position transform.position when you set the final position of the object.

#

I'm assuming it's following world zero.

verbal dome
#
// Direction from target object to hit point
Vector3 dir = hit.point - targetObject.position;
// Project that direction so that it "snaps" to the axis
Vector3 projectedDir = Vector3.Project(dir, transform.up);
// Add the projected vector to the target object's position to get the final world space position
Vector3 newPos = targetObject.position + projectedDir;```
Uhh something like that?
#

Could be completely off, I need some ☕

nocturne kayak
verbal dome
wise hearth
#

JustAGirl Can someone help me with my lights dont work? When I drag in lights they dont give off any light

wintry quarry
wise hearth
#

oh i didnt know that, ty

verbal dome
#

@nocturne kayak Btw just fixed a major typo in the snippet, was using hit.point inside Project instead of dir. Edited

wise hearth
verbal dome
#

Post your question in lighting channel and we can take a look. Also provide the info that Praetor was asking

shy lichen
#

someone free to dm for help?

frosty hound
shy lichen
#

Done already but it was jumped over with a lot of messages

#

Sorry

cosmic quail
shy lichen
#

Thought not to spam here

nocturne kayak
#

Just to confirm, what you did essencially was get the relative position from hitPoint from the targetObject and turn it into dir

#

then project dir on the axis handle's up vector

#

and get the relative position again through newPos?

#

Now it works as intended

#

But for some reason it's affecting ALL objects with this script

verbal dome
#

You're welcome

nocturne kayak
verbal dome
#

Planes are infinitely "wide" so I guess you are hitting the plane of both of those handles

nocturne kayak
# nocturne kayak

This has me very confused, shouldn't my script component only afect it's direct parent?

verbal dome
#

Should probably do some kind of distance check and check which one is closer

#

Busy right now can't check out the code

nocturne kayak
#

Understandable, but the plane's only being created when i click one of them

livid gale
#

Hello. I was trying to create an input manager script + basic movement script(called fps controller) in 3d. However, everytime I try to start it, I am getting an error. which I'll share in photo. Below are links to the two scripts.
https://hastebin.com/share/pugerogaqi.csharp
https://hastebin.com/share/zibirofazo.csharp

wintry quarry
wintry quarry
#

you need to look at that in your script

livid gale
#

How is it null?

wintry quarry
#

presumably this returned null

#

i.e. that action name doesn't exist in your actions asset

livid gale
#

Is it case sensitive?

wintry quarry
#

of course

livid gale
#

Might be the cause

wintry quarry
#

and make sure there are no spaces in the name or something

livid gale
#

It's on autosave

wintry quarry
#

and that the correct actions asset is assigned

livid gale
#

it also says this

#

However I have a maincamera with a tag

wintry quarry
#

and look at the filename and line number of the error

polar acorn
# livid gale it also says this

There is no Camera attached to the Player game object, but a script is trying to access it. You probably need to add a camera to the game object Player, or the script needs to check if the component is attached before using it.

wintry quarry
#

the fact there is a camera in your scene is not relevant

livid gale
#

So maincamera has to be inside player?

polar acorn
wintry quarry
polar acorn
#

If you don't want to use the Camera component on this object, don't

thorny basalt
livid gale
#

I have to, otherwise how will I be able to use the look action?

polar acorn
livid gale
#

What if I changed it to Camera.main?

polar acorn
#

Sure, that would no longer be trying to read the Camera component of this object

#

it would instead be referencing a Camera on an object tagged MainCamera

livid gale
#

Well, that brings me back to the original problem. lookAction is still null

polar acorn
#

Perhaps log those values right before that line so you can make sure they're what you expect

livid gale
#

I'll try

#

Nope

polar acorn
#

Nope what

wintry quarry
# livid gale Nope

Make sure you look at the inspector for the object this script is on too. The action names are serialized. So you might have changed it in the inspector

wintry quarry
#

also not clear what it is you are saying you tried there

livid gale
#

All I had to do was fix a typo in the inspector..

shy lichen
#

Hello everyone Im kinda short on time so ill ask this in bigger message.So i have project for university bout making mobile games,i have 2 problems SpriteRenderer updates in Menu but not as physical object https://youtu.be/b8YUfee_pzc?si=txIGHsLc3-HUOtWP&t=19256 (i timestamped video on this part) and here is code im using rn following tutorial GameManager: https://hastebin.com/share/esocofovuy.csharp
CharacterMenu: https://hastebin.com/share/kosemanupu.csharp
Weapon:https://hastebin.com/share/wudekiwone.csharp
Second problem is enemy not following player:
part of video bout enemy:
https://youtu.be/b8YUfee_pzc?si=X_idqVFXWJbaSuYg&t=15057
scripts
Enemy:https://hastebin.com/share/uyotivekov.csharp
Mover:https://hastebin.com/share/rimesefohu.csharp

2024 edit!
I've got a new course teaching multiplayer here on youtube! Check it out
https://www.youtube.com/playlist?list=PLmcbjnHce7Scovukpm2UbvBmhPKvM52uD

--- Livestream alert ----
I'm live every Saturday morning, come say hello
https://www.twitch.tv/n3rkmind

This is a full release of an Top Down RPG course made in Unity 2017

Here's a link ...

▶ Play video

2024 edit!
I've got a new course teaching multiplayer here on youtube! Check it out
https://www.youtube.com/playlist?list=PLmcbjnHce7Scovukpm2UbvBmhPKvM52uD

--- Livestream alert ----
I'm live every Saturday morning, come say hello
https://www.twitch.tv/n3rkmind

This is a full release of an Top Down RPG course made in Unity 2017

Here's a link ...

▶ Play video
livid gale
polar acorn
shy lichen
#

Menu one updates but in game stays the same picture

#

as weapon sprite

#

instead of chaniging like on menu one

polar acorn
#

So, it's logging the name of the current sprite, and it's showing as staff_2. Since the object in the inspector shows a sprite of staff_1, one of two things is happening. Either spriteRenderer is not referring to this object, or something else is changing the sprite after the log occurs.

#

Since spriteRenderer is public, another script could be changing it, or calling SetWeaponLevel to change it back

shy lichen
#

Okay thanks(sry didnt make any kind of game in 7 years).Seems like puting it private doesnt change much so ill try to update SetWeaponLevel script

polar acorn
#

If it's private and nothing is giving you a compile error, then that would eliminate the possibility of something else changing spriteRenderer, so we can now eliminate the first possibility of it referring to a different object. That'd mean something else is changing it after the sprite change, back to Staff_1. SetWeaponLevel seems the most likely culprit, since it changes the sprite without logging anything

eternal falconBOT
shy lichen
#

xd

polar acorn
#

You called up the bot, you just have to read what it says

shy lichen
#
public void LoadState(Scene s, LoadSceneMode mode)
    {
       SceneManager.sceneLoaded -= LoadState;

        if (!PlayerPrefs.HasKey("SaveState"))
            return;
        Debug.Log("Load");

        string[] data = PlayerPrefs.GetString("SaveState").Split('|');

        gold = int.Parse(data[1]);
        exp = int.Parse(data[2]);
        if(GetCurrentLevel() != 0)
        player.SetLevel(GetCurrentLevel());
        weapon.SetWeaponLevel(int.Parse(data[3]));


        
    }
polar acorn
shy lichen
#

so it calls value of of state when player moves to another level or when i restart game.Seems like this isnt problem.Ill try to check other things.Thanks for your time anyway.

hollow quest
#

anyone knowns how to setup neovim to work with unity?

pulsar meteor
#

is there any good public varible turtorial or somthing like that cus i just dont understant it

nocturne kayak
#

Well, other than programming basics that'd be hard to help with

deft grail
#

public just means its accessible in other scripts

pulsar meteor
#

but i cant ever get it in my other scripts

nocturne kayak
#

How are you trying to access these variables?

deft grail
pulsar meteor
#

i wil look

nocturne kayak
#

public doesn't mean that you can access it from any other script in the engine, that'd be a mess on the backend

#

it just means that when you reference that specific script, you CAN read\write those variables

pulsar meteor
#

i delted that

#

but it was like or with Serileized field or a whole line that says where it was and than what var

viscid needle
#

hey can anyone help me know how to make the Y axis of the pipe in Flappy bird change once per every spawn

deft grail
polar acorn
viscid needle
#

mine changes every update

deft grail
#

instead of in Update

viscid needle
#

ok will try

deft grail
pulsar meteor
#

public MyScript script; what is what i dont understant you exactly

deft grail
#

its the same as public int myInt;

steep rose
#

you can access public variables from each script, if the script has none, you cannot access the variables

deft grail
#

this public can be either private or [SerializeField] private to show it in the inspector

pulsar meteor
#

what is MyScript

steep rose
#

replace it with whatever script you want to access

polar acorn
worldly frost
#

yo, my code is crashing unity whenever i run it (2d android game)

async Task SignUpWithUsernamePasswordAsync(string username, string password)
    {
        try
        {
            await AuthenticationService.Instance.SignUpWithUsernamePasswordAsync(username, password);
            Debug.Log("SignUp is successful.");
        }
        catch (AuthenticationException ex)
        {
            Debug.LogError("Authentication Exception occurred.");
            Debug.LogException(ex);
            _errorText.text = ex.Message;
            _errorText.gameObject.SetActive(true);
            return;
        }
        catch (RequestFailedException ex)
        {
            Debug.LogError("Request Failed Exception occurred.");
            Debug.LogException(ex);
            _errorText.text = ex.Message;
            _errorText.gameObject.SetActive(true);
            return;
        }
        catch (Exception ex)
        {
            Debug.LogError("An unknown exception occurred.");
            Debug.LogException(ex);
            _errorText.text = "An unknown error occurred.";
            _errorText.gameObject.SetActive(true);
            return;
        }
        SceneManager.LoadScene(3);
    }
deft grail
#

it can be a Rigidbody2D it can be a BoxCollider it can be anything that you want to reference

pulsar meteor
polar acorn
steep rose
#
//first script
public float cookies;
public float carrots;
public float hamburgers;
//second script
public Firstscript _firstscript;

_firstscript.cookies/carrots/hamburgers // etc

deft grail
pulsar meteor
steep rose
deft grail
worldly frost
pulsar meteor
steep rose
#

im glad it helped you but its still best to !learn

eternal falconBOT
#

:teacher: Unity Learn ↗

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

pulsar meteor
frosty hound
# worldly frost mb

Which Debug.LogError is running? You can't expect someone to just guess these things.

steep rose
#

you do understand its a course right?

pulsar meteor
#

yea

steep rose
#

what does that even mean

polar acorn
#

You are at the basics, so a video that goes over the basics is exactly your speed

steep rose
#

and please elaborate what you mean by "the first how unity looked"?

pulsar meteor
#

i mean how to place things and change locations

steep rose
#

you mean use public variables?

vocal fable
#

why it doesnt work

#

index outside bounds of array

#

but it isnt

polar acorn
wintry quarry
steep rose
#

i couldnt know since im not the greatest guesser

polar acorn
#

You're getting the seventh element of a list with 6 things in it

vocal fable
#

what

wintry quarry
#

1 is the second

#

6 is the 7th

vocal fable
#

but the others worked like normal

wintry quarry
#

arrays all work this way

polar acorn
wintry quarry
#

this is the normal way

vocal fable
#

this is bolt up

polar acorn
wintry quarry
polar acorn
#

Wait, yes, wrong bolt

#

Bolt Back

steep rose
#

5 is clipin

polar acorn
vocal fable
#

ohhh

#

sorry im dumb

#

i thought this was 1

#

so it was shoot

#

but i forgot to set it

#

yes it was 5

worldly frost
#

so i cant see any errors in the log

frosty hound
#

Install the Logcat package, and run it while your phone is plugged in to see the console.

worldly frost
#

like the whole editor freezes bruh

#

i gotta kill it using task manager after

frosty hound
#

Then how do you know it's that code that is freezing it?

viscid needle
#

how to share code here?

frosty hound
#

!code

eternal falconBOT
worldly frost
viscid needle
frosty hound
#

What does the button's code look like? Is it just calling ithat function?

viscid needle
wintry quarry
viscid needle
#

would removing it work?

wintry quarry
#

yes

worldly frost
# frosty hound What does the button's code look like? Is it just calling ithat function?

oops forgot this code (im sleepy)

public void SignUp()
    {
        if (IsValidEMail(_email.text))
        {
            string passwordCheck = IsValidPassword(_password.text);
            if (passwordCheck == "valalaid")
            {
                Debug.Log("egg");
                SignUpWithUsernamePasswordAsync(_email.text, _password.text);
            }
            else
            {
                _errorText.text = passwordCheck; // Set the text to the new value
                _errorText.gameObject.SetActive(true); // Show the text
            }
        }
        else
        {
            _errorText.text = "Invalid email format."; // Show error message for invalid email
            _errorText.gameObject.SetActive(true);
        }
    }
wintry quarry
viscid needle
#

I tried but didnnot unedrstand

#

thank you

polar acorn
worldly frost
wintry quarry
worldly frost
#

oops i thought u where other guy

worldly frost
frosty hound
polar acorn
worldly frost
worldly frost
#

and it only logs the egg

frosty hound
#

Can you log AuthenticationService.Instance at the top of the function?

#

So you can verify that you actually have a reference to it

viscid needle
frosty hound
#

No, log it

#

Debug.Log (AuthenticationService.Instance);

viscid needle
wintry quarry
#

very quickly it's going to get out of hand

polar acorn
viscid needle
#

ohh thanks

polar acorn
#

So, after 2 seconds, you will be spawning one every frame

frosty hound
polar acorn
#

after 2.03 seconds, you'll be spawning two per frame

#

and so on

viscid needle
worldly frost
# frosty hound No, log it

if i comment out the authenticationservice.instance.SignInWithUsernamePasswordAsync thing it doesnt crash, logging it as you said outputs: Unity.Services.Authentication.AuthenticationServiceInternal
and then it proceeds to do the sign up succesful stuff

frosty hound
#

That's not at all what I asked?

polar acorn
#

I asked it

#

Just to confirm if it was that function and not the other IsVald___ functions

worldly frost
#

which i did

#

and i commented out the signinwithusernamepasswordasync so it doesnt crash

worldly frost
viscid needle
#

hey umm... my pipeSet's Y value us changing every instant, I want it to change with every instantiate how do I do that

wintry quarry
polar acorn
#

Is that what you want spawnPipe to be doing?

viscid needle
wintry quarry
polar acorn
wintry quarry
#

it's jsut moving some existing object

viscid needle
wintry quarry
polar acorn
viscid needle
polar acorn
#

If so, you should probably call the function something else

wintry quarry
deft grail
wintry quarry
#

why are you doing this in the "moveLeft" script

wintry quarry
#

You need to look at the script that actually spawns things

#

this is the script that moves the pipes

viscid needle
polar acorn
wintry quarry
viscid needle
#

ok

#

wait a minute

polar acorn
#

You should name the functions what they actually do

viscid needle
#

here better?

polar acorn
#

Still doesn't make much sense

viscid needle
polar acorn
#

The fact that this is your second attempt at naming it shows that you don't seem to know what that line of code does

steep rose
#

pipemove would be better

polar acorn
#

What do you think this line of code does:

pipeSet.transform.Translate(-1f, Random.Range(-4f, 4f), 0);
viscid needle
#

did it

polar acorn
viscid needle
#

so how do instantiate it

polar acorn
#

Call Instantiate

viscid needle
#

ok I will try to understand it again

hallow acorn
#

hey how can i check if all my referenced colliders (trigger) enter my other collider?

#

i need it for my placing system which checks if all "anchors" touch the floor

verbal dome
#

Probably easiest to do an OverlapBox/Sphere/Capsule/Circle2D for each of those

#

Actually not OverlapX but CheckX

steep rose
#

you could also use the triggers ontriggerenter to check if any objects go in it

verbal dome
#

You can also manually check it in OnTriggerEnter/Exit but that sounds like more work

hallow acorn
verbal dome
#

Since you need to keep track of each collider, as opposed to instantly checking it with a physics query

steep rose
#

just use an array or list or smth

#

I do not see the need for hostility

verbal dome
# hallow acorn what?

I'm saying, do a physics query (for example Physics.OverlapSphere) on the points you need to check

fluid lagoon
#

hi i added my freind to my orginization so we can work on a game togather how can he accses it from the unity hub he can see it on the cloud but there is not option in the hub
please help us so we will be able to work on a game togather

verbal dome
#

The other option is to add each collider into a list in OnTriggerEnter and remove it in Exit
And when you want to place the object, check if the list has all of the colliders

hallow acorn
steep rose
# hallow acorn how do i check for the list?

public List<GameObject> ListObjects = new List<GameObject>();
this is to create it
then you just do a for/while loop and check if there are more than x amount then do something

#

make sure you do List.add to add things to it

#

also keep in mind i am not the best at lists 😅

hallow acorn
viscid needle
#

hey can anyone pls help me how to finish this codehttps://paste.ofcode.org/VBRBVEEFtBUcx6ZcMDYB4M

#

it has something to do with angles I just dont know what

#

I have to fill it with a quartanion rotation

#

the rotaions are supposed to be all 0, pls help fasttt

edgy prism
#

Hello, im working on a 2D game and in it I am spawning "pillar" gameObjects for the player to walk around, currently I am tracking its sorting order and putting it above player if behind it and below if its infront like so:

void Update()
    {
        if (player.transform.position.y > transform.position.y)
        {
            //Player is above Pillar
            this.GetComponent<Renderer>().sortingOrder = 1;
        }
        else
            this.GetComponent<Renderer>().sortingOrder = -1;
    }

The issue is when I have to pillars next to eachother they still clip, I was hoping someone could tell me the best approach to fix that, my current thinking is to also check in this function for adjacent pillars and change the sorting order accordingly

viscid needle
#

hey can anyone pls help me how to finish this codehttps://paste.ofcode.org/VBRBVEEFtBUcx6ZcMDYB4M
it has something to do with angles I just dont know what
I have to fill it with a quartanion rotation
the rotaions are supposed to be all 0, pls help fasttt

steep rose
hallow acorn
modest dust
# hallow acorn but cant i just create a list like this: `public List<BoxCollider> Colliders;` a...

As Osmal pointed out, the easiest way to do it is with Physics.CheckBox. Here's a simple example:

bool CheckAnchors(Vector3[] anchorPositions, Vector3 halfExtents, int groundLayermask)
{
  foreach(Vector3 anchorPosition in anchorPositions)
  {
    if (!Physics.CheckBox(anchorPosition, halfExtents, layermask:groundLayermask))
    {
      return false; // Anchor not touching ground, no need to check the rest.
    }
  }

  return true;
} ```
modest dust
steep rose
hallow acorn
#

can i just do it with a child for each collider?

steep rose
#

can you use overlapsphere/box/etc to check a gameobjects child?

wintry quarry
hallow acorn
#

can i just check for the name of the childs?

wintry quarry
#

they will tell you which colliders overlap, full stop

edgy prism
steep rose
wintry quarry
steep rose
wintry quarry
# hallow acorn why not?

very slow, causes garbage collection, and is just... not the way. references are better in every way basically

edgy prism
hallow acorn
steep rose
hallow acorn
#

bro what the actual f do you mean

steep rose
#

what?

#

wdym

#

am i missing something here?

verbal dome
hallow acorn
#

how does it help in any way to determine if everyone of the colliders entered collider "whatever" if i give the same tag to all of them?

hallow acorn
verbal dome
#

I don't know about the tags, I didn't suggest that. I suggested using lists which you ignored

steep rose
#

you check if the gameobject has the tag and if it does you add that gameobject to the list

#

i explained it a while ago

hexed terrace
steep rose
#

there is definitely better way instead of tags but i dont know them rn

hallow acorn
steep rose
verbal dome
hallow acorn
edgy prism
tulip nimbus
wintry quarry
#

it's a project setting that changes how the camera renders your sprites. It sorts them in order by the y axis

edgy prism
edgy prism
tulip nimbus
#

So that means, because it is not spawned/loaded yet, it cannot take any Transform attributes since its technically not in the game?

wintry quarry
#

You need to get the reference another way

#

for example, assign it at reference in your code after spawning the object

tulip nimbus
#

like in Awake()?

wintry quarry
tulip nimbus
#

ah okay thanks!

wintry quarry
#
MyScript spawnedObj = Instantiate(myPrefab);
spawnedObj.someReference = aReferenceIHave;```
spiral abyss
#

hi i was wondering how to make a colidor move with animation?

verbal dome
#

What is this for though? Not sure if it can reliably produce collisions for you if you move it with anims

steep rose
spiral abyss
steep rose
#

If you do not know what transforms are or dont know how to move them I suggest you !learn

eternal falconBOT
#

:teacher: Unity Learn ↗

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

steep rose
#

But as Osmal said this may not produce good collisions

spiral abyss
steep rose
#

Do you know what a vector3 is?

spiral abyss
#

semwhat

steep rose
#

I suggest you learn via link

spiral abyss
#

ok ty

jade tartan
#

Hello again, I'm trying to create a boolean variable to allow my player character to be deactived and reactivated, but i don't know what to put in the coding to define how to define the true and false of this boolean https://hastebin.com/share/izodetiwid.csharp

past drift
#

Good evening. I am still quite new to the subject. But I would love to create my own mobile game. It should be a kind of AFK RPG. Could someone kindly tell me what I need for it?

steep rose
#

but for an RPG you would have to ask yourself what you need, what you want the game to look like, etc

swift elbow
#

some more info on what youre trying to do exactly would be nice

#

or how youre trying to achive this

polar acorn
steep rose
polar acorn
eternal falconBOT
#

:teacher: Unity Learn ↗

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

devout flume
polar acorn
#

Idle games are actually a non-trivial problem, you'll learn things like data persistence, real time synchronization, and how to handle numbers too big to fit in a float. Still, it's not an insurmountable goal for a first project, it's not massive in scope, it just has some quirky technical problems other game genres don't

steep rose
#

like AFK games? (oh you mean idle games nvm then)

polar acorn
#

I am literally playing Cookie Clicker right now

steep rose
#

and or your attention span

ruby python
#

Just wondering, is it possible to use DOTs to just spawn specific things and use 'regular' Instantiating etc. for other things? (essentially mixing the two methods)

ivory jasper
#

what is this thing that keeps appearing even when i delete it

polar acorn
ivory jasper
#

oh

#

do I have to worry about it

polar acorn
#

Do you want your UI to work

ivory jasper
#

probably

polar acorn
#

Then you probably want to stop deleting it

ivory jasper
#

good idea

waxen adder
#

How can I tell what objects are being considered as obstacles for a navmesh?

teal viper
waxen adder
#

Ah, right so I can search for those

#

Interesting. So originally I was using a navmeshmodifier to achieve the result of the obstacle (with carve on). Had to end up switching that because there doesn't seem to be a reference to it I can get via script? Edit: it might be entirely possible that I'm missing a using statement, since modifiers require an additional install.

This does beg the question. What exactly is the point/difference between the two?

teal viper
waxen adder
#

Interesting. Is it possible to retrieve these modifiers via script? I didn't see any option pop up with intellisense

teal viper
#

Don't trust a stranger though, read the docs

teal viper
waxen adder
#

From the looks of it, I should be using obstacles. Modifiers seem to be for more interesting changes to the navmesh. The example used in the docs is a "lava" area, rather than something like a wall

teal viper
#

If the wall is static and never gonna change, I think you should use a modifier

waxen adder
#

Right now, it's static

#

Will probably change that in the future though

verbal dome
#

Using a modifier with a non-walkable area override should do it

waxen adder
#

Gotcha, my problem now is trying to reach the modifier component via script. The docs are proving to be a maze on this.

verbal dome
#

Try UnityEngine.AI.NavMeshModifier ?

waxen adder
#

Nothing comes up after .AI

#

Adding it regardless says that it doesn't exist

silk night
#

if its not, install it

gaunt solstice
#

I implemented all this so now I just need to know how to get it to make a new random point if the dot is < 0

waxen adder
teal viper
verbal dome
#

If with "dot is < 0" you mean it's in an undesirable direction

silk night
waxen adder
teal viper
silk night
teal viper
#

If it's older than 2022, you should probably upgrade

silk night
#

2.0 is 2023.2.0a18+

waxen adder
#

2022.3.16f1

verbal dome
#

Actually I'm on 2021 and not using that package lol, so it's probably not even supposed to be UnityEngine.AI.NavMeshX

verbal dome
#

There we go, sorry for misleading

#

Didn't realize I'm on the older version

waxen adder
teal viper
silk night
#

what IDE are you using? usually you can let your IDE auto import the needed stuff

waxen adder
#

WAIT

teal viper
#

Unless you explicitly use Navigation.NavMeshModifier every time.

waxen adder
verbal dome
waxen adder
#

angery

#

The IDE sees it now

#

Ty all for helping me on this

#

What is the area type in nav mesh modifiers? I see it's an int, but the values you see in the editor are, well, words. Is this like a layer mask or something?

verbal dome
#

It's an integer but displayed as the name of the area

wintry quarry
#

in the inspector you see a nice dropdown yea

verbal dome
#

And in some places - such as what Praetor linked - it's a mask so sort of similiar to layermask yeah

waxen adder
#

Gotcha. Trying to see how to implement this in a way that's readable, instead of plopping a magic number and calling it a day XD

verbal dome
#

Try NavMesh.GetAreaFromName

waxen adder
#

Is there an "AreaMask" type like there is "LayerMask"? Not getting AreaMask to show up in intellisense

verbal dome
#

Dont think so, just an integer

waxen adder
#

Or is it okay to combine the functionalities of the old system with the new(ish) ai.navigation?

verbal dome
#

I think it still uses parts of the navmesh class but I could be wrong

#

Doesnt it use the same systems for configuring area names, costs etc?

dry sparrow
#

Hello, can someone help me with very basic things? I don't know hoe to explain the problem with text so I would like to show

waxen adder
verbal dome
waxen adder
lofty lintel
#
 float moveX = 0f;
 float moveY = 0f;

 

 //Sprinting.--------------------------------------------------------------
 if (Input.GetKey(KeyCode.LeftShift) && stamina >= 2.2f && rb.velocity.magnitude > 0)
 {
     //getting camera animation----
     animator.SetTrigger("Running");
     //speed becomes boostedSpeed----
     speed = speedBoost;
     //reducing stamina on cost of runcost---
     stamina -= runCost * Time.deltaTime;
     if (stamina < 0) stamina = 0;
     staminaBar.fillAmount = stamina / maxStamina;

     //new Color(234, 244, 84) - normal color.
     //run - new Color(187, 194, 79) - sprint color.

     staminaBar.color = new Color(187f / 255, 194f / 255, 79f / 255);
     //reseting Coroutine----
     if (recharge != null) StopCoroutine(recharge);
     recharge = StartCoroutine(RechargeStamina());
 }
 else
 {
     animator.SetTrigger("EndRunning");
     speed = 30f;
 }
 //StaminaBar Color Configuration.------------------
 if (stamina <= 0)
 {
     staminaBar.color = new Color(131f / 255, 132f / 255, 120f / 255);
 }
 else if (!Input.GetKey(KeyCode.LeftShift) && stamina > 2.2f)
 {
     staminaBar.color = new Color(234f / 255, 244f / 255, 84f / 255);
 }
 //Movement On Keys.------------------------------
 if (Input.GetKey(KeyCode.W)) moveY = +1f;
 if (Input.GetKey(KeyCode.S)) moveY = -1f;
 if (Input.GetKey(KeyCode.A)) moveX = -1f;
 if (Input.GetKey(KeyCode.D)) moveX = +1f;
 //PlayerMovement.----------------------------------------
 Vector3 moveDir = new Vector3(moveX, moveY, 0f).normalized;
 

 Vector2 targetVelocity = moveDir * speed; // your movedirection * speed
 Vector2 velocityDiff = targetVelocity - rb.velocity;
 rb.AddForce(velocityDiff * acceleration);```

Hello, How could I fix this jittering guys, sometimes it looks smooth but in the end its kinda weird.
verbal dome
#

The NavMesh class is still relevant.
The "old" version is just the NavMeshComponents package that you had yo manually download. The NavMesh itself predates that

wintry quarry
lofty lintel
#

oh wait

#

I had extrapolation

#

Interpolation is worse

wintry quarry
#

leave interpolation on

waxen adder
lofty lintel
wintry quarry
# lofty lintel This is with interpolation
       if (PlayerRotates)
        {
            Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            transform.rotation = Quaternion.LookRotation(Vector3.forward, mousePos - transform.position);
        }```
#

because you're directly modifying the Transform here, you're breaking the interpolation

verbal dome
#

Ah there we go

lofty lintel
wintry quarry
#

it doesn't matter

#

you're breaking both of them

#

with your rotation

lofty lintel
#

mouse rotation?

wintry quarry
#

Whatever it is

#

you are directly modifying the Transform

#

it breaks interpolation

lofty lintel
#

so basically

#

I should change it to velocity?

wintry quarry
#

no

#

that doens't make sense

dry sparrow
#

I have an object in root with Transform and basic Shooter script that takes bullet prefab and instantiate it giving the bullet velocity and parenting it to itself. In the play mod I dragged it on the scene to see what s happening and saw that it jiggering its position in scene tho in the inspector it is not

wintry quarry
#

this is what you want

lofty lintel
verbal dome
#

Wouldnt that be MoveRotation?

lofty lintel
#
if (Input.GetKeyDown(KeyCode.X)) { if (PlayerRotates) PlayerRotates = false; else PlayerRotates = true; }
//Player Rotate Follows Mouse.---------------------------------------------------------------
if (PlayerRotates)
{
    Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);

    Vector3 lookDir = mousePos - transform.position;
    rb.rotation = Mathf.Atan2(lookDir.y, lookDir.z) * Mathf.Rad2Deg;
    
    //transform.rotation = Quaternion.LookRotation(Vector3.forward, mousePos - transform.position);
}```
#

So like this?

wintry quarry
#

yesd

verbal dome
#

Or does rb.rotation not break interpolation

wintry quarry
#

it doesn't break interpolation

lofty lintel
#

Should I use inter or exterpolation

wintry quarry
#

interpolation

verbal dome
#

Extrapolation kind of overshoots, trying to guess where you should be

#

While interpolation just lerps between the last and current position

lofty lintel
verbal dome
#

Could be a camera issue too 🤔

wintry quarry
#

how are you doing camera folow

lofty lintel
#

Cinemachine

wintry quarry
#

make sure the brain is in LateUpdate or SmartUpdate mode

lofty lintel
#

I have no brain

#

i mean

wintry quarry
#

you have to have a brain

lofty lintel
#

where tf is brain i dont even know

wintry quarry
#

it's on the camera

waxen adder
#

Is there some way I can reach into these AreaMasks, so I can record the list of them?

wintry quarry
lofty lintel
lofty lintel
wintry quarry
#

ok that should be fine...

lofty lintel
wintry quarry
#

double check the player inspector?

dry sparrow
lofty lintel
wintry quarry
# lofty lintel

also try disabling the rotation code for a sec to see if it does anything?

lofty lintel
#

ok

waxen adder
lofty lintel
#

oh

#

it does

wintry quarry
#

Also set this to pivot

verbal dome
#

What info do you want to store about the areas? @waxen adder

lofty lintel
wintry quarry
lofty lintel
#

Alright wait

waxen adder
lofty lintel
#

like this?

dry sparrow
verbal dome
lofty lintel
#

rotation doesn't work like that

#

oh wait

#

different clip wait

lofty lintel
wintry quarry
lofty lintel
#

and?

waxen adder
#

Meh, I think I'll just keep things simple and do area comparisons with GetAreaFromName

lofty lintel
#

by default it's true so

wintry quarry
#

that should do it..

lofty lintel
#

that didn't do it

wintry quarry
#

is SHould Rotate printing?

lofty lintel
wintry quarry
#

show the rest of the code?

lofty lintel
#

wait

lofty lintel
ivory bobcat
eternal falconBOT
wintry quarry
#

maybe the Animator is interfering now? 🤔

lofty lintel
#

I think code too large

lofty lintel
#

Animator only triggers on Shift

wintry quarry
#

see if disabling the animator does anything

lofty lintel
#

Ok i'll try that

verbal dome
lofty lintel
#

I'll try that too wait

wintry quarry
#

oh yeah

lofty lintel
#

didn't work

wintry quarry
lofty lintel
#

wait look

#

Tried using last code u told me and it works but well wrong way

lofty lintel
wintry quarry
lofty lintel
#
rb.rotation = Mathf.Atan2(lookDir.y, lookDir.x) * Mathf.Rad2Deg;
#

90 to where

wintry quarry
#

rb.rotation = Mathf.Atan2(lookDir.y, lookDir.x) * Mathf.Rad2Deg + 90;

#

possibly subtracting 90 lol

#

one of those

lofty lintel
#

actually

#

I did this haha

#
 rb.rotation = Mathf.Atan2(lookDir.y, lookDir.x) * Mathf.Rad2Deg + 270;
#
  • 90 would work
verbal dome
#

Yeah thats the same as -90

lofty lintel
#

I think my math is mathing rn so I understand that last part

lofty lintel
#

since this is learning process maybe could u guys like explain what was going on?

#

a little?

#

to not waste ur time much

wintry quarry
#

you didn't have interpolation on your rigidbody, so you got stuttering

#

because the physics engine runs out of sync with the framerate of the game

#

interpolation smooths that

#

but if you directly modify the Transform, it breaks the interpolation

#

so we just had to make sure you had interpolation on and you weren't breaking it

lofty lintel
#

what does Extrapolation do

wintry quarry
#

if you moouse over them there's a little explanation

#

interpolation is a little behind, extrapolation is a little in the future

#

both smooth it out

lofty lintel
#

Moving code to Fixed update

#

I know difference that

#

Update runs more frames and that

#

was it like necessary to move the rotation code to fixedUpdate?

wintry quarry
#

for MoveRotation it is

lofty lintel
#

Extrapolation goes better with Update
However its opossite for interpolation

wintry quarry
#

my understanding is .rotation would go better in Update and MoveRotation would go better in FixedUpdate

lofty lintel
#

im using .rotation in fixedupdate and it works best

wintry quarry
#

so my understanding may be off. Maybe it's different for 2D

lofty lintel
#

So would this work same for that stick? should I put interpolate on it too right

#

just did and it worked! thank you so much <3

dry sparrow
#

Another question. I have an Object that have "Gravity" script attached:

private float _gravity = -10f;
private Rigidbody2D rb => GetComponent<Rigidbody2D>();

void Start() {
    rb.velocity = new Vector2(rb.velocity.x, rb.velocity.y + gravity);
    }```
"gravity" is -10. So the object at default have y velocity -10.
And it have another object as a child that spawns objects and giving them x velocity via "Speed" script attached to this objects.: 
```cs
...
[SerializeField] private GameObject projectile;
public Vector2 direction = new Vector2(1, 0);
...

GameObject _proj = Instantiate(projectile);
_proj.transform.parent = transform;
_proj.transform.localPosition = Vector2.zero;

Speed _projSpeed = _proj.GetComponent<Speed>();
_projSpeed.horizontalSpeed *= direction.x;
_projSpeed.verticalSpeed *= direction.y;```
The "Speed" script:
```cs
public float verticalSpeed = 0f;
public float horizontalSpeed = 0f;
private Rigidbody2D rb => GetComponent<Rigidbody2D>();
void Start() {
    rb.velocity = new Vector2(rb.velocity.x + horizontalSpeed, rb.velocity.y +            verticalSpeed);
    }```
The issue is that instantiated objects have the velocity, but they don't moving at all. They move when they attached from its parent tho, is this because the parent is changing it's position via velocity? If so, how do I make children attach to it but have velocity and move as expected?
verbal dome
#

Not sure how the rb acts when it's a child though, especially if the parent is moving. I usually avoid that

#

Ah, 2D kinematic bodies can be moved by velocity so that part should be good

dry sparrow
#

That helps, but I afraid that could affect the perfomance too much?

verbal dome
#

What helped? Making it not kinematic?

dry sparrow
#

Yeah, I made projects dinamic

#

but if there are a lot of them

#

it could affect perfomance Im afraid

verbal dome
#

Why would the docs say that kinematic rb2d can be moved by velocity 🤔 I wonder if thats even correct

dry sparrow
#

it is moving, but only if it independed

verbal dome
#

IIRC 3d bodies ignore velocity when kinematic so there is some inconsistency between 2d and 3d

verbal dome
dry sparrow
#

yes

verbal dome
#

I dont see why you need them as children

dry sparrow
#

so they was destroied when parent is destroied

#

I could make a list tho I think

verbal dome
#

Alright, maybe keep them separate and yeah destroy them from a list

#

Another option is to give the player an empty parent that acts as the container for everything related to the player

#

Then destroy that parent

dry sparrow
#

I also want them to move with its parent, and feel like there will be alot of unnecesery code if I attach them

verbal dome
#

And have the bullets directly as children of the parent. So "siblings" of the player

steep rose
#

if not then idk lmao

verbal dome
#

Sure, its just confusing that kinematic means different things

#

Unity could name things anything they want regardless of the underlying physics engine

steep rose
#

its all a facade

verbal dome
#

Generally speaking rigidbodies shouldnt be children of other rigidbodies

#

Unless the child is kinematic

dry sparrow
#

yeah I got it,

lunar sand
#

I'm trying to make a simple script where when I press R the object's Y rotation value goes back to 0, I have made this code so far but it says "The name 'gameObj' does not exist in the current context" how would I go about defining it?

#

public class Resetcar : MonoBehaviour
{
void Update()
{
if (Input.GetKey(KeyCode.R))
{
gameObj.transform.eulerAngles.y = 0;

    }

}

}

wintry quarry
#

But also you don't need that at all

#
Vector3 eulers = transform.eulerAngles;
transform.eulerAngles = new Vector3(eulers.x, 0, eulers.z);```
#

gameObject would be redundant here

lunar sand
queen adder
#

    float LastFrameTheNavmeshWasUpdated;
    public void UpdateNavmesh()
    {
        if(LastFrameTheNavmeshWasUpdated != Time.frameCount)
        {
            LastFrameTheNavmeshWasUpdated = Time.frameCount;
            StartCoroutine(NavmeshUpdateCoroutine());
        }
    }```any better pattern to make sure this coroutine doesnt run multiple times no matter how many times it was called in a single frame?
wintry quarry
queen adder
wintry quarry
#

Also this:

float LastFrameTheNavmeshWasUpdated;```
#

should be int

queen adder
#

usually when some obstacle was built/destroyed

wintry quarry
#

because frameCount is an int

queen adder
#

oh yes, lemma change that

#

but yea, is this the best pattern?

#

I tried flipping a bool and checking in Update() but that was probably worse, is it?

wintry quarry
queen adder
#

yea that was my original

#

but it is way too active

wintry quarry
#

whgat you have now is fine I would say

queen adder
#

Also you're 🤏 close to 300k (I dunno how you can be so active, I barely added 7k messages on one of the server I am usually staying in)

wintry quarry
queen adder
#

Hi

sand snow
#

can anyone help me, im having an issue when my character walks into a wall it slightly changes its rotation, my game is 2D, how do i fix this?

sand snow
sand snow
fiery plume
#

Using the line renderer i have drawn Lines. The line renderer is on a UI Object in the Canvas and i want the lines to either follow the camera or the object its attached to but if i turn off world space the lines will no longer render and im unsure what to do?

sour palm
#

you can change the Canvas to use "World Space" instead of "Screen Space" (then position the line renderer)

stuck palm
#

how could you copy something to the clipboard?

#

like a room code or something

placid elm
#

Is there a way to make if statement that will trigger on collision with objects of all tags but not one specific?

swift elbow
swift elbow
#

compare the one you dont want and do nothing, and in the else statement, do what you want

stuck palm
swift elbow
stuck palm
fickle halo
#

Why must i do float x = 10f instead of float x = 10?

#

it feels redundant since I already specify float

swift elbow
languid spire
#

because 1.1 is a double and you cannot automatically downcast

devout flume
# fickle halo Why must i do `float x = 10f` instead of `float x = 10`?

Good question, I've never had to use f in C/C++ every time I was defining a float. I don't know if you have to do it in those languages too (if yes, then it's just a legacy from those languages), if not, there must be a reason why they chose to do it that way at Microsoft. Maybe it's to differentiate between float and double, as historically floats are using IEEE754 on 32 bits, whereas doubles are using IEEE754 on 64 bits. Nonetheless the compiler should be able to detect from the type itself.

devout flume
#

Decimal values may be defaulted to double.

languid spire
#

they are

devout flume
#

I'm just wondering why the f isn't strictly mandatory in C/C++

languid spire
#

because C and C++ are not type safe, C# is

devout flume
#

The same behavior applies to those languages, but they implicitly cast to float whenever you assign something to a float. Microsoft decided to not implement this indeed

eternal needle
languid spire
#

C and C++ do not care about data types. you can declare a variable as a long and use it as a double, the only thing that matters is the size of the type

eternal needle
#

From double to float, data is lost

languid spire
burnt vapor
devout flume
#

Yes, they chose safety, not a bad thing imo

languid spire
#

number of times I've had to debug bad C++ because of unintentional downcasts

burnt vapor
#

Also, my guess the reason why you do it here and not with things like integers is because of floating point inaccuracies

#

So explicitly specifying ensures this is not the case

devout flume
#

Is C# using a whole environment to run? (Like Java's VM)

languid spire
devout flume
#

Oki that's what I thought

#

Thanks

wary gale
#

Hi, does anybody know how i can make the yellow UI image be under/behind the gray UI image? I've tried changing the z positions but had no luck. Thanks

#

Do i have to make seperate layers?

slender nymph
#

not a code question. but UI is drawn in the order it is in the hierarchy, so things higher up the hierarchy are drawn first, which means lower in the hierarchy are drawn last (or on top)

wary gale
#

ah, thought this channel was for unity beginners in general. Thanks for the help

slender nymph
#

nope, the code in code-beginner means it is a code channel

wary gale
#

oh really, i would have never guessed that

timid ember
#

in the calculator, I wanted to make one which can solve numbers without taking a big if chain for 2 numbers.

answer= System.Convert.ToDouble(new System.Data.DataTable().Compute(CurInput,""));

this shows error that I can not convert dbnull into double.

#

i imported system.data into assets and gave reference.

#

public class Clac : MonoBehaviour
{
    public TextMeshProUGUI disptext;
    private string CurInput="";
    private double answer;

    public void ButtonTap(string val)
    {
        if(val== "=")
        {
            ans();
        }
        else if(val== "C")
        {
            Clear();
        }
        else
        {
            CurInput=val;
            UpdateDisplay();
        }
    }

    public void ans()
    {
        try
        {
        answer= System.Convert.ToDouble(new System.Data.DataTable().Compute(CurInput,""));
        CurInput=answer.ToString();
        UpdateDisplay();
        }
        catch(System.Exception)
        {
            CurInput="invalid";
            UpdateDisplay();
        }
    }
    public void Clear()
    {
        CurInput="";
        answer=0.0;
        UpdateDisplay();
    }
    public void UpdateDisplay()
    {
        disptext.text = CurInput;
    }
}```
#

if i remove try and catch exception, the code gives that error
with this, it simply says invalid

sand snow
#

how do you guys make your code like that in discord

steep rose
#

!code

eternal falconBOT
eternal falconBOT
sand snow
#

'''cs
//void FixedUpdate()
{
Vector3 playerInput = new Vector3(Input.GetAxisRaw("Horizontal"), 0, 0);
transform.position = transform.position + playerInput * speed * Time.deltaTime;

 Vector3 playerJump = new Vector3(0, Input.GetAxisRaw("Jump"), 0);
 transform.position = transform.position + playerJump * jumpForce * Time.deltaTime;

}
'''

timid ember
#
Debug.Log ("nice")
#

use `

steep rose
#

read the bot

#

look under Inline Code

timid ember
#

u used ', use ` thrice at the top and then at bottom

languid spire
timid ember
#

bottom too

steep rose
#

he just has to read the bot

steep rose
cosmic dagger
#

they are backticks. the tilde key (on an american keyboard) . . .

timid ember
sand snow
#
//  void FixedUpdate()
 {
     Vector3 playerInput = new Vector3(Input.GetAxisRaw("Horizontal"), 0, 0);
     transform.position = transform.position + playerInput * speed * Time.deltaTime;


     Vector3 playerJump = new Vector3(0, Input.GetAxisRaw("Jump"), 0);
     transform.position = transform.position + playerJump * jumpForce * Time.deltaTime;
 }
#

lets go i did it

steep rose
languid spire
steep rose
sand snow
steep rose
#

and applying it by time.daltatime

cosmic dagger
steep rose
sand snow
#

i am?

timid ember
steep rose
cosmic dagger
# sand snow i am?

you are setting the transform.position; this is manipulating the transform, which does not involve the physics engine at all . . .

sand snow
#

and if i manipulate the gravity is falls faster

steep rose
sand snow
#

ill put the whole code in so you can see

steep rose
#

then use its Addforce() or Velocity to move around

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

public class PlayerMovement : MonoBehaviour
{
    public Rigidbody2D rb;
 public float speed;
    public float jumpForce;
    public float gravityForce;
   private void Start()
    {
       rb = GetComponent<Rigidbody2D>();
    }
 void FixedUpdate()
    {
        Vector3 playerInput = new Vector3(Input.GetAxisRaw("Horizontal"), 0, 0);
        transform.position = transform.position + playerInput * speed * Time.deltaTime;

        Vector3 playerJump = new Vector3(0, Input.GetAxisRaw("Jump"), 0);
        transform.position = transform.position + playerJump * jumpForce * Time.deltaTime;
    }

}
#

thats all my code

sand snow
#

gravityForce does nothing i forgot to delete that

timid ember
steep rose
#

best you !learn

eternal falconBOT
#

:teacher: Unity Learn ↗

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

livid gale
#
    {
        lastPos = controller.transform.position;

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

        move = transform.right * x + transform.forward * z;

        controller.Move(speed * Time.deltaTime * move);
}

I've got this code here. Is there any way I could only check the x and z of the controller instead of the entire 3d vector?

languid spire
sand snow
steep rose
cosmic dagger
steep rose
#

as i stated you really need to !learn

eternal falconBOT
#

:teacher: Unity Learn ↗

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

cosmic dagger
languid spire
timid ember
#

yes

steep rose
languid spire
#

then you jst need a simple string parser

livid gale
timid ember
steep rose
languid spire
steep rose
timid ember
livid gale
languid spire
#

until they hit =

timid ember
#

k, im gonna try it out

steep rose
#

you assign it a new vector

livid gale
#

Thank you!

steep rose
eternal falconBOT
#

:teacher: Unity Learn ↗

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

timid ember
languid spire
steep rose
steep rose
languid spire
timid ember
#

or java

languid spire
steep rose
#

looks neat

languid spire
#

equation solver

timid ember
#

does it directly compute like cs answer= System.Convert.ToDouble(new System.Data.DataTable().Compute(CurInput,""));

or does it use if statements for each operation and stops when it hits "="?

languid spire
#

Hey, I wrote it, It's much cleverer than either of those

steep rose
timid ember
steep rose
#

beginners dont know what debug.log() is

#

i dont know what you're on about 😁

timid ember
#

mb yo

languid spire
steep rose
#

you were slaving away at that program

timid ember
#

i think asking chatgpt for help was a massive mistake

steep rose
languid spire
timid ember
#

it overcomplicated the code and i already forgot what i know

steep rose
#

welp better luck next time, dont use it

timid ember
#

the more i ask it to do it beginner style, the more it complicates itself

steep rose
#

stop asking it

timid ember
#

also, does dangling else work in c#

steep rose
#

you literally have your own server to ask in

timid ember
steep rose
#

so he should have explained it to your level then

timid ember
#

had to ask him to explain how he would explain to a 5 year old

steep rose
#

well my point still stands, best not use gpt

#

you have what, like 20,000 people in here?

#

i can assuredly say to you that gpt is nothing compared to that

hexed terrace
timid ember
#
using System.Collections;
using System.Collections.Generic;
using System.Data;
using UnityEngine;
using TMPro;
using UnityEngine.UI;

public class Clac : MonoBehaviour
{
    public TextMeshProUGUI disptext;
    private string CurInput="";
    private double answer;

    public void ButtonTap(string val)
    {
        if(val== "=")
        {
            ans();
        }
        else if(val== "C")
        {
            Clear();
        }
        else
        {
            CurInput=val;
            UpdateDisplay();
        }
    }

    public void ans()
    {
        try
        {
        answer= System.Convert.ToDouble(new System.Data.DataTable().Compute(CurInput,""));
        CurInput=answer.ToString();
        UpdateDisplay();
        }
        catch(System.Exception)
        {
            CurInput="invalid";
            UpdateDisplay();
        }
    }
    public void Clear()
    {
        CurInput="";
        answer=0.0;
        UpdateDisplay();
    }
    public void UpdateDisplay()
    {
        disptext.text = CurInput;
    }
}
#

Are there any errors with respect to unity?

steep rose
#

why ask us when the console tells you

#

if you get any errors or warnings, the console will scream at you

hexed terrace
#

It's also against the server rules to

  • ask for help with code generated by AI
  • give help to code generated by AI
timid ember
#

is that also against the rules

hexed terrace
#

If it's tutorial code... your question then doesn't make sense. 😄

shell sorrel
#

its really bad code either way

#

it makes no sense and abuses things that will just makes it harder to find bugs

#

like that try catch will just mask what is going on

timid ember
#

so ill have to make if chains
man 😦

#

welcome to unity for me i guess

shell sorrel
#

and is like the worst way to convert a string to double

timid ember
#

does writing a code in vs and vsc differ by any means?

shell sorrel
#

its jsut a tool to write code, all code unity sees compiles the same way

timid ember
#

k, tnx

hexed terrace
#

VS is better than VSC, if you have the choice

shell sorrel
#

realy does not matter for most, what ever is easier to get setup is what i would go with

zinc grove
#

What’s the write approach to start programming as a beginner

devout flume
# timid ember does writing a code in vs and vsc differ by any means?

Just an editor, one may become handier than another depending on what you're looking for, I personally prefer vscode as it's lightweight, and supports every language because it's just a text editor. You can configure it to mimick a real editor designed for specific languages but yeah

timid ember
#

i forgot evrything abt html

#

but yea python is good for base and C

#

learning either is easy

devout flume
#

C is very good to understand memory and how things work

timid ember
#

id prefer c

devout flume
#

C seems easy but it can become a hassle as it lets you do whatever you want

timid ember
#

C# is the better looking java

hexed terrace
shell sorrel
#

no point going through a whole path, if you all you want to do is make a game that uses C# or C++

#

you will learn more if you can apply the skills to a project you care about and find intersting then just going through the motions