#💻┃code-beginner

1 messages · Page 405 of 1

swift crag
#

procgen is non-trivial

#

and very little is completely "done by yourself"

#

I read articles about the "wave function collapse" scheme before implementing it; i didn't invent it on my own

queen adder
#

so its okay to watch tutorials and copy what they do/write?
since i can not think of anything writing it from scratch sadly lol

#

i wouldnt even know how to throw tiles from a tilemap into the map

swift crag
#

start by just figuring out how to fill an area in a tilemap with one tile

#

then pick tiles randomly

#

then start doing more complicated things

queen adder
#

90% of coders basically are just good Googlers that can make different code together 🤣🤣🤣

#

You are suffering from imposter syndrome

#

meaning what

cosmic quail
#

not even pros who havent made a procedural world before know how to do a procedural generated world without specifically studying it by googling tutorials and stuff for it and copying stuff

queen adder
#

i think ill just break it down to small pieces and ask chatgpt to explain to me this small steps, then try to write it myself

like i just asked chatgpt "how to create a chunk"
then next will be "how to set tiles from tilemaps into chunks"

#

and so on

swift crag
#

i would not advise using a spam generator to write your game

cosmic quail
timid hinge
#

hi guys can someone explain me something

wanton kraken
#

Why is this invalud? Please excuse my ineptitude
f(MathF.Abs(CatBody.velocity.x)>) <= 0.1)

timid hinge
#

how can i add sound to an animation on unity?

wanton kraken
#

add an audio component and then reference it in the script, i think. you should watch a youtube video on it

wintry quarry
languid spire
#
>) <=

what do you think this does?

wanton kraken
#

fuck my bad LOL

vast vessel
#

guys how do i fix this 😵

swift crag
#

you can't, really

wintry quarry
swift crag
#

the version of C# that Unity uses doesn't allow for struct field initializers

#

they can only start out with the default value

short hazel
#

Field initializer is using = ... directly on fields

vast vessel
#

okay thats not an issue, ig ill just pass a default value in the constructor

short hazel
#

Note that in the C# version Unity uses, structs cannot have default parameterless constructors

vast vessel
#

can structs be seralized in the editor?

queen adder
#

Is it possible to define spawn points for the input manager?

wintry quarry
vast vessel
#

ty

wintry quarry
queen adder
#

Meaning for the player joining

queen adder
wintry quarry
#

What do you mean?

#

It's not something built into anything

#

you would create it

queen adder
#

Oh right okay

swift crag
queen adder
#

Thanks

swift crag
#

it'll send a message to MonoBehaviours on the same game object as itself

swift crag
#

You can react to the join/leave there

#

you can also subscribe to those events, yeah

queen adder
#

Thanks alot

#

idk i feel like giving up to even start making my game
i learned so much hours of c#, but chatgpt aswell as tutorials seem to be cheaty
Since i can copy, but not actually write or change stuff accordingly.

I would need help on like very meter of that developement lol. Damn game dev is hard and frustrating. Hm.

#

Theres no "cheating" as long as you're learning and having fun who cares

pliant oyster
#

How do I do a "Please press a key" thing for rebinding controls? I tried googling but only found outdated information about it being impossible.

wanton kraken
wanton kraken
pliant oyster
#

I know there's "Input.GetKeyDown" but how do I use it? And how do I make the environment that allows it to listen for the keypress?

magic panther
#

Dlich, if you're reading this, I fixed it.
The function was just poorly written, so I started over and now it works (it seems so, at least)

languid spire
pliant oyster
#

I want to use the new one but I don't really know my way around. I haven't found what the way is to find how to do it.

pliant oyster
#

I will assume I might have to start a coroutine on button click, then stop it once it captured and set the key as well as the image, or default to the previous key on leave?

pliant oyster
#

Do I have to separately install something for it?

#

It talks about "Input System Package" and IIRC packages are installable optional content.

languid spire
#

yes, in the package mange look for tyhe Input System package

pliant oyster
#

Thank you!

#

This one?

#

Or is that the old one?

summer stump
#

That is it

#

The old one is not a package

#

You can tell because anything that says Input SYSTEM is the new one. The old is the Input class and InputManager class

#

I guess also that the description says "a new input system"

pliant oyster
#

Thank you!

languid spire
swift crag
#

The old system is built into the editor, and configured from the "Input Manager" section of the project settings

pliant oyster
#

I had some experiences of falsely assuming which led to some projects I spent a long time on being permanently ruined, so I make extra effort to avoid misunderstandings.

summer stump
#

@pliant oyster That sounds like you are not using Version Control.
Stop everything and set that up now

languid spire
swift crag
#

you should be able to hit your project with a sledgehammer without any risk of losing your work

#

i can't imagine not using version control nowadays

pliant oyster
#

I'll use github and periodically upload my project there.

#

Thanks!

vital tangle
#

hello

#

i have a basic trouble

#

consider i have a raw image in UI

#

at position x = 0

#

position y = 0

#

and height and widht are equally 50

#

now i want to use my mouse scroll to increase or decrease this size and width equally

vital tangle
#

suppose i got the mouse up and down values

queen adder
#

So you want to zoom?

vital tangle
#

sorry for bad internet

turbid bridge
#

does anyone have any information on how i can set a drop down in a menu to translate my game from english to other languages please

swift crag
languid spire
# vital tangle

then calculate a % increase/ decrease based on current sizes

short hazel
# vital tangle sorry for bad internet

Sending it all in one message would probably solve it, instead of hitting Enter every five words.
Shift+Enter to add a newline without sending the message

vital tangle
#

here is something i am doing

turbid bridge
vital tangle
#

i am pretty bad with such stuff

#

From what I was thinking
i thought of taking ratio by ratio value and then increase decrease that to generate the new zoom value

languid spire
vital tangle
languid spire
#

google is your friend

vital tangle
languid spire
#

we are here to point you in the right direction, not take you by the hand to cross the street

vital tangle
#

🙃

languid spire
vital tangle
#

i know right

#

tho i am developing a sort of tool right now rather than a game

vital tangle
queen adder
#

Bro I've made rpgs and never needed math

languid spire
queen adder
#

You don't need math knowledge for gamedev 90% OF THE TIME

languid spire
#

no, wrong, 99% of ANY dev is math

queen adder
#

At worst you just copy paste copy frommonline

languid spire
#

that ain't dev and if you think it is you are very much mistaken

queen adder
#

I made a old school Zelda clone for college nevervneeded any crazy math

vital tangle
languid spire
#

ah, so now we've gone from 'no math' to 'no crazy math' which is it?

vital tangle
#

i usually serialize my animations and using encryption algorithms

queen adder
#

You don't need to know trig or whatever unless you are making a particle system or physics or whatever and 90% of it is copy paste

vital tangle
#

for the best efficiency you need the best way to compute stuff

#

there maths come in handy

#

Dealing and Quaternions and stuff as well

queen adder
#

i think i give up at this point. I have my dream game in mind, but then its the question if others would even enjoy it. Unity and coding seem to be fun, but its frustrating to be just a copy/paster from the very beginning not knowing how/if it affects your game. I guess it would take months or years to make a beginner 2d game. Like i know what i want to create/do, but there is not even an idea of how to put it into the game code wise. Im also bad at designing graphics and dont want to use open source ones that everyone uses. Guess its just not meant to be at this point and i should maybe do something else. Code small projects with c# general or just focus on one sub-part of game dev like creating pixel art and selling.

Thanks for all your help guys. Rip.

frank zodiac
#

i added a debug for my Keyboard.current.leftMouse.isPressed and for some reason when I click my mouse once it prints 7 times.. why is that?

#

I only want it to print once

frank zodiac
wintry quarry
#

you're cehcking if the button is currently held down with that code

frank zodiac
wintry quarry
languid spire
frank zodiac
queen adder
tough lagoon
languid spire
queen adder
#

Yes its "math" but if thats something that you consider worth mentionjng...

queen adder
#

People ask if you need to know "math" they are asking if they need to know physics, not basic pemdas

vital tangle
#

i wrote 4,000 lines of code just to make a file browser that opens and browse assets
and you cant even imagine what algorithms i used in that process

#

you have to agree
if you are not good with maths
you cannot even do all these for loops

languid spire
tough lagoon
# vital tangle tho i am developing a sort of tool right now rather than a game

It's important to mention, a tool or asset store creator creating tools for devs, understanding optimization, math, structures etc is even more important. Gamedevs will rely on your tools (and, in a way, expertise) to make their games. And to avoid a lot of support calls, the more you can do early on the better.

I had to brush up on three.js euler to quaternion and deconstructing/reconstructing matrixs this week for a webAR thing. But it's good to learn.

I'll also go against the grain and say to ask AI about it from time to time. Don't take it as valid, but it can help nudge you in the right direction if you don't have a lot of time to really breakdown the subject.

rich adder
finite hornet
vital tangle
tough lagoon
vital tangle
#

also I am 18

rich adder
vital tangle
#

yo we can have a debate on this if you say ripped off

finite hornet
rich adder
#

could've at least changed the UI of it so I wouldnt recognize it lol

tough lagoon
#

🍿

vital tangle
#

ripped off??

#

you dummy

rich adder
vital tangle
#

you dont even know how much it takes to build one

rich adder
vital tangle
rich adder
#

makes me question how much of this is your code..

languid spire
vital tangle
#

i wasnt talking about this file browser

frank zodiac
#

if a gameobject is active then the Start() function runs, then i make it inactive then i set it to active will the Start() function run again? or does it run only on the first frame?

vital tangle
#

the browser i use to itterate between files i loaded from the filebrowser

swift crag
#

The Start message only gets sent to a component once.

vital tangle
#

i was talking about that

frank zodiac
swift crag
#

OnEnable gets sent many times, though (:

#

Note that OnEnable gets called immediately after Awake -- and not alongside Start

rich adder
swift crag
#

(assuming that the component is enabled when it gets instantiated)

vital tangle
#

i can show proof as my script

rich adder
vital tangle
#

take a look at it

finite hornet
# vital tangle yoooo

html and css don't requre that much for a simple front end site, unless you did something wrong

frank zodiac
swift crag
rich adder
#

yeah I wish I wouldn't have seen that lol

vital tangle
#

you guys literally went against me

#

what wrong did i do?

rich adder
#

nobody is against you my guy

#

You said "I made a file browser" I saw the two matched, thought it was funny.. let move on lol

languid spire
finite hornet
# vital tangle 🥲

Honestly you worked hard, it is visible in the code. But if you knew a bit more it would be easier on you, like spamming if statements is never good my man

tough lagoon
#

I wouldn't worry about it too much, we are all somewhere on our journey, and gotta pick which path in front of us is the most interesting (and avoid those that are distracting)

swift crag
#

i should point out that this is obviously an interface for an asset ripper

vital tangle
#

not a ripper

short hazel
#

It's the same thing

#

It opens files which you aren't legally supposed to

languid spire
swift crag
#

It's using UAE to extract data from a built Unity game. All of the code is copy-pasted logic to display different kinds of Unity assets.

short hazel
#

You cannot get help about it here

vital tangle
rich adder
#

stiches a bunch of assets together phew I wrote 4000 lines of this amazing code, math is hard

swift crag
#

it's mostly copy-pasted logic with a few unique lines for each kind of asset

vital tangle
#

i did rather not hear stuff about any effort i did

#

thanks for that

rich adder
swift crag
swift crag
#

to answer your original question: calculate the ratio of the short side to the long side. use that to scale how quickly you change the short side's size

vital tangle
#

ok i backdown from my statement

swift crag
#

a 30x50 image, for example, would grow 60% as fast on the minor axis

vital tangle
#

thanks for the guide

wintry quarry
vital tangle
#

bye!

vital tangle
swift crag
#

🤫

#

I have my own sins (:

vital tangle
#

man damn that shit is unreleased

swift crag
#

this server simply doesn't allow you to discuss or get help with such things

#

along with modding in general

vital tangle
#

so that's doesnt make any issues for me

vital tangle
#

want to ask something

high lava
#

ive been trying to get unity (this version in particular because it's the one i need for an ultrakill level editor kit) and it keeps getting stuck in the validation stage of the editor application, i've searched online and tried solutions i found but none worked. does anyone have any idea on how i could fix this

warm condor
#

Hey, so I am well aware that when you use the invoke method in unity, you will have to define what the name of the function. However, is there a way you can use the invoke method by executing one line of code instead of calling a function?

burnt vapor
#

If you want an easier time combine Invoke with nameof to avoid confusion with magic strings

warm condor
#

delegate? never heard of it. What is it and how do you use it?

pliant oyster
#

I set up the new input system like the earlier linked tutorial said, now how do I capture the user's input and tell the system "hey, the user is now using a custom keybind for this action"?

burnt vapor
vast vessel
#

hey guys. why cant i add the OnDrawGizmos callback to my MonoBehaviour?

slender nymph
#

you can, you just have to actually write the entire method signature

warm condor
#

is there a way I can do this? My goal with this is to not create a useless function that executes only one line of code.

vast vessel
woeful terrace
#

Sorry for the headache I might be about to drop...

I am trying to make a movement script and right now implementing a sprint function so that I can go faster if needed. However when I press shift I stop instead of speeding up like how I should. Below is my code and the component in the unity program.

https://gdl.space/jotobabite.cs

swift crag
#

!code

eternal falconBOT
floral panther
#

I come from gamemaker, is it possible to create global variables, or have a variable be easily accessible by other scripts?

slender nymph
#

if a variable is public you can access it by getting a reference to the object that it is on

woeful terrace
# swift crag !code

Ah thanks updated the message (Can't get the txt file away tho for some reason)

warm condor
swift crag
languid spire
swift crag
#

Add some braces.

warm condor
swift crag
#

Notice how this is not what you intended.

#

C# does not care about indentation. That middle else is associated with the previous else if.

woeful terrace
swift crag
#

you know { }

wintry quarry
#

yeah this is looking very python

swift crag
#
if (!sprinting) {
  // ...
} else {
  // ...
}
swift crag
rocky canyon
#

whitespace nightmares!

warm condor
swift crag
#

Invoke does not work like that.

woeful terrace
swift crag
#

This has nothing to do with System.Action.Invoke, which executes an action

#
System.Action foo = () => Debug.Log("Hi");
foo.Invoke();
swift crag
#

It's very easy to lose track of what goes with what.

#

Note that your IDE's formatter will reveal this

swift crag
warm condor
woeful terrace
swift crag
#

Calling Invoke() on an action runs it instantly. C# has no notion of "waiting"

#
IEnumerator Wait(System.Action callback, float delay ) {
  yield return new WaitForSeconds(delay);
  callback();
}
#

(you can simply use the () operator here)

woeful terrace
#

@swift crag Def works now thank you so much!

marble gorge
#

do any of you guys know how to use JU

swift crag
peak blaze
#

!cd

#

!cs

eternal falconBOT
magic panther
#

Quick question. In my roomManager script (https://gdl.space/kumejesuli.cs), I create a Room roomSave variable which I set to be the room we load. Later on I use this fact to load the roomSave to make a Restart mechanic. Everything works as intended, except for the fact that the roomSave is updated along with whatever it was saved as. I had this problem when I started learning javaScript, and this is caused by me saving the reference to that room, not the actual room's data. If there is a way to set roomSave to a COPY of whatever object we set it as, I'd be thankful to anyone who tells me. (I asked chatGPT and he broke everything, as always)

swift crag
#

You need to be able to either:

  • create a new Room that's a copy of an original
  • serialize and deserialize your Room
#

(these are roughly the same thing)

magic panther
#

you mean add a Room variable for every single room?

#

like, make every one a prefab?

swift crag
#

You can't "make" a prefab at runtime

#

and I didn't suggest adding more room variables

swift crag
#

Is this a GameObject/some other unity object?

magic panther
#

a class that stores objects inside, an object

swift crag
#

Show me the Room class.

white orbit
#

question how do i learn C# like the most optimal way.

magic panther
floral panther
magic panther
#

gpt suggests adding something like this

#

which could work, those are all the public variables we use

magic panther
floral panther
#

youtube

#

or

#

somewhere else

#

idk

swift crag
eternal falconBOT
#

:teacher: Unity Learn ↗

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

swift crag
#

Microsoft Learn will teach you C# more generally

#

I would lean towards the latter

swift crag
#

You can Instantiate the entire room to create a new object. This may be appropriate.

#

However, this would break those children links

#

I would suggest trying to separate the mutable and non-mutable parts of Room

#

So, you've got that "interacted" field -- that changes as you play, right?

magic panther
#

the second you make a move it changes. I mostly added that for debugging purposes in case the level is Clear'd instantly

swift crag
#

If most of the Room stays the same, give it a "Restore" method that resets those mutable parts back to the defaults.

swift crag
magic panther
#

what changes is mostly the children array and all the data of everything inside it

swift crag
#

well then that gets a lot more complicated!

#

I guess you could parent all of the rooms to an object and Instantiate the entire thing

magic panther
#

would just making all rooms prefab variants of the main Room prefab an option? Or is this a cowardly approach

uncut shoal
#

Hello! I'm using Graphics.DrawMeshNow but nothing is being drawn?

void Update()
{
    foreach (var chunk in chunks) 
    {
        // set first shader pass of the material
        worldMaterial.SetPass(0);
        // draw mesh at the origin
        Graphics.DrawMeshNow(chunk.mesh, chunk.position * 16, Quaternion.identity);
    }
}
swift crag
#

I'm unclear on the scope here.

uncut shoal
#

When I put the mesh on a mesh renderer it renderers fine, but when I do this, it doesn't do anything.

#

No errors, either.

magic panther
swift crag
#

That does not answer my question. Do you need to remember how rooms are connected together?

#

children is a field on Room, so...maybe you do?

magic panther
#

rooms are not connected besides being on the rooms list in roomManager

swift crag
#

You can instantiate all of your rooms (thus creating new ones) and use those for gameplay. When you restart, destroy the instances.

magic panther
#

brb 2 mins

magic panther
#

ok im back

magic panther
magic panther
swift crag
#
Room instanced = Instantiate(originalRoom);
#

This will copy the game object and all components on that game object, including the Room component.

magic panther
swift crag
#

this would cause every room to copy itself, and every copy would copy itself, and ...

swift crag
#

When the game restarts, destroy those copies and make new ones.

magic panther
#

so I should make an originalRooms array, add the rooms there

#

and then... hold on a second

frank zodiac
#

why did i just get 44 errors when i opened my project??

magic panther
rocky canyon
magic panther
#

ok, @swift crag I think we can use the originalRooms array, as the only place it's used so far is adding all rooms to it on roomManager's Awake.

pliant oyster
#

I set up the new input system like the earlier linked tutorial said, now how do I capture the user's input and tell the system "hey, the user is now using a custom keybind for this action"?

frank zodiac
summer stump
magic panther
magic panther
#

man, why is this so weird

gusty lotus
#

Is there a way to check if a navmesh has been built?

rich adder
rocky canyon
gusty lotus
remote osprey
#

!code

eternal falconBOT
rocky canyon
#

Chicken, you been here a long time.. u dont haave any of those bookmarked by now?

rich adder
#

or memorized

#

gdl.space is so ez

rocky canyon
#

i got hatebin memorized but that website only works half of the time for me 🤣

remote osprey
#

Sorry...

#

Done

rocky canyon
#

Niice lol

rich adder
remote osprey
rocky canyon
#

i couldnt say ive never nested a coroutine in a coroutine but im interested to see what other have to say

frank zodiac
rocky canyon
#

nice 👍

#

an empty console is a happy console

languid spire
vital tangle
#
    public GameObject scrolluv;
    void Update()
    {
        if (Input.GetAxis("Mouse ScrollWheel") > 0f  || Input.GetAxis("Mouse ScrollWheel") < 0f)
        {
            //Get the mouse position on the screen and send a raycast into the game world from that position.
            Vector2 worldPoint = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            RaycastHit2D hit = Physics2D.Raycast(worldPoint, Vector2.zero);

            //If something was hit, the RaycastHit2D.collider will not be null.
            if (hit.collider != null && hit.transform.gameObject == scrolluv)
            {
                Debug.Log(hit.collider.name);
            }
        }
    }```
#

i have this code to tell me if i am scrolling it tells me if the object i am scrolling on with my mouse is

#

but it doesnt work

#

it always displays the value even when my mouse is not hovering the 2d object

rich adder
summer stump
vital tangle
summer stump
#

What does it say it hit?

#

The name. In the console

vital tangle
#

the name in the console

#

it says it hit

#

when the mouse is not even at that point on screen

summer stump
#

What. Is. The. Name

wintry quarry
vital tangle
wintry quarry
summer stump
#

There we go. You have an object called texture image

wintry quarry
#

probably a background image or something

summer stump
#

You could put that to ignore raycast layer

vital tangle
summer stump
#

Ui is still a gameobject....
Everything is a gameobject

wintry quarry
vital tangle
wintry quarry
#

why

summer stump
vital tangle
#

so that when the ray collides it would return me that object

wintry quarry
#

UI should not have a collider

rocky canyon
#

UI elements automatically have their own detection

wintry quarry
rich adder
#

use the Pointer interface

rocky canyon
vital tangle
#

now what to do?

wintry quarry
#

what are you trying to do exactly

#

which objects are you trying to detect

vital tangle
#

if the cursor points on some other object and scroll
it should not affect anything and the void must return

wintry quarry
vital tangle
#

more like a image zoom in and zoom out

wintry quarry
#

and set up the "OnScroll" event

vital tangle
#

i want the image to zoom when the mouse is scrolled onto it

wintry quarry
#

or make your script implement IScrollHandler

vital tangle
#

let me do it

vital tangle
#

worked

#

thanks for the help

#

your the best

queen adder
#

Yeah I had some sort of thing like this in mind, thank you for providing an example

brisk ruin
#

Guys why the post process volume component doesn't affect my scene 💔

slender nymph
#

also this is a code channel

brisk ruin
rocky canyon
#

holy gamma batman

vital tangle
#

hey ummm

#

i have a scroll rect

#

and i have an image

hexed terrace
#

speak in full sentences, and remember this is a code channel.

summer stump
vital tangle
#

is there a way i can scroll by clicking in the image
rather than dragging the viewport

the problem i am facing is that

i selected the image as the content in scroll rect and the borders as the viewport

the problem i am facing is that
i cant use scroll by clicking on the image
but i can use scroll by clicking on the viewport

any fixes

#

(Also sorry for my previous half sentences)

hexed terrace
#

not a code issue, -> #📲┃ui-ux make sure the image has the target raycast bool ticked

high lava
#

ive been trying to get unity (this version in particular because it's the one i need for an ultrakill level editor kit) and it keeps getting stuck in the validation stage of the editor application, i've searched online and tried solutions i found but none worked. does anyone have any idea on how i could fix this

high lava
#

oh mb

frank zodiac
#

guys for me to run animation events do i have to have the component that has the function attached to the gameobject with the animator or is it okay if its from another object

wintry quarry
frank zodiac
orchid pewter
#

shows me this when i launched my project, i can show code

#

!code

eternal falconBOT
iron wing
short meadow
#

!code

eternal falconBOT
iron wing
wintry quarry
wintry quarry
#

Yes

orchid pewter
#

welp

wintry quarry
#

I'm explaining to you why you're seeing errors

orchid pewter
timid oriole
#

I know this might be a silly area to ask but any chance anyone can help me with circuit analysis? Figured since most of you code it would be a good place to ask as most comp sci students take it

wintry quarry
orchid pewter
#

wait nvm chat gpt just helped me

#

robot>human

wintry quarry
#

I mean, sounds like ChatGPT actually got to see the code

orchid pewter
#

ur saying robot isnt better then human?

summer stump
orchid pewter
#

what

wintry quarry
slender nymph
rich adder
final kestrel
#

Living up to the name

summer stump
orchid pewter
#

ur saying i look like a troll?

#

kyro TV you have smt to say?

fickle plume
#

@orchid pewter Move on, please.

orchid pewter
#

Okay, im sorry

short meadow
#

Hello, I'm having problems displaying a scriptable object.

Item.cs scriptable object: https://pastebin.com/wPTb0GNQ
DisplayItem.cs my UI script that is attached to a parent container containing various UI elements related: https://pastebin.com/7AYTcENL

Errors in code: NOTE that none of my Debug.Logs display.
NullReferenceException: Object reference not set to an instance of an object
DisplayItem.UpdateUI () (at Assets/Scripts/DisplayItem.cs:28)
DisplayItem.Start () (at Assets/Scripts/DisplayItem.cs:20)

I made an Item 'Charcoal'. Picture in editor: https://jumpshare.com/s/pRkx8vrNxiXfYrqo8ioT
I've setup UI elements to display here along with buttons. The buttons have their On Click() function referencing DisplayItem.IncreaseQuantity() and DisplayItem.DecreaseQuantity().
Pics of my Hierarchy and Inspector of 'Item Line' which contains my 'DisplayItem' script: https://jumpshare.com/s/CqQZl0fLoYCshBoZCVgu

Hopefully I made it easy to navigate. It's my first time posting in here.

slender nymph
#

itemAmountText is null and is never assigned to anywhere

summer stump
#

itemAmountText is null, for that exception
Ah 🦥

short meadow
#

right but I'm assigning it on line 28 itemAmountText.text = item.itemQuantity.ToString(); I believe that would convert the Int variable from item class which is assigned 0 default. Am I misunderstanding something here?

slender nymph
#

no you are accessing its text property on that line, not assigning to that variable

rich adder
languid spire
slender nymph
#

the variable is null so accessing its text property is causing the NullReferenceException

slender nymph
#

don't worry, when you figure out how to assign it, you'll end up with another because icon is also null. then after fixing that you'll have to do the same for craftingSize

short meadow
#

I had those set to public and referenced before. I have no memory of making them private. My brain is super fried but it's fixed, thank you guys.

slender nymph
#

you can still make them private, they just need to be serialized. you can slap a [SerializeField] attribute on a private variable to be able to assign to it in the inspector. that way other objects cannot reassign the variables as well

short meadow
#

So if I want my buttons to work to increase or decrease the amount I can't Serialize the Quantity right? Because then the buttons wouldn't be able to interact with the script? So in that specific case it would need to be public?

slender nymph
#

huh? your buttons would call the Increase and Decrease Quantity methods. as long as those are public they can be accessed by the button(s)

short meadow
#

Ohhhhhhhhhhhhh I see now that makes sense. Thank you, I was looking at this like "How is this working???"

slender nymph
#

and public variables are serialized already. that's how they appear in the inspector

short meadow
#

so is it just best practice to Serialize anything that you wouldn't want to be public? I may go back to the documentation on access container types.

rocky canyon
#

i feel ur overcomplicating it.

short meadow
#

probably

slender nymph
rocky canyon
#

you use different protection for w/e the variable is needed for

#

public, private, static, [SerializeField] private, etc

slender nymph
#

best practice is to have no public fields at all though. use properties if you want other objects to have access

rocky canyon
#

^ thats a big beginner mistake.. eeven me

short meadow
#

That makes sense.

rocky canyon
#

thats why u use private variables unless that variables needs accessed outside the class from somewhere

#

then if u need to expose a private variable for ease to you (assigning it for example) u can use the SerializeField attribute

#

its easy in the beginning to make everything public soo u feel like u have full control in the editor

#

u can also hide a public variable if u need to.

short meadow
#

I feel like I went over all of this in the Create with code course and it's only now really sinking in. (I am a conversational learner though so that checks out). Thanks for your patients and explanations guys.

rocky canyon
#

that eureka moment.. i call it a click moment

#

that happens alot... when ur learning.. usually delayed a bit after learning something lol 😅

#

w/ coding stuff makes more senes when u start implementing it hands on.. and some things u learn u dont really need to know until you do

eager spindle
#

before I started learning game dev full time it took me a long time before it clicked on how I can break down the game I want to make into approachable tasks which felt like a wall before I could start any project

#

but by doing more fun projects more things will click

rocky canyon
#

absolutely agree, thats why i ended up with dozens of prototypes.. i may never use em but i learned alot from each one

short meadow
#

I'm noticing something weird. Are scriptable objects supposed to be used as a save-load type thing? When I increase or decrease in play mode and then exit and reload it stays exactly where it left off. I assumed since everything else is temporary during play mode it would have set those values back.

#

Or is that a bug in editor?

eager spindle
#

saveload thing? not really they're just for storing data
yes, scriptable objects are supposed to not revert once play mode is ended. but in the built version, scriptable objects will revert to their original state.

#

youll have to do additional work to get scriptable objects to revert to their original state.

short meadow
eager spindle
#

generally the process for save/load is to write to a file. this is up to you on how you'd like to do it.

if you publish to steam you can use steam's sdk to save player data. if your game is synced to an online network, thats an entirely new topic. the overall process is to write your own code to save/load to a file.

#

the file you save/load to can be plaintext for now, encrypted if you know what you're doing, or the overkill solution is to start your own db locally

#

in my current game I'm storing my stuff in plaintext 😦

rocky canyon
#

speaking of.. is it bad to use scene indices over other methods like string names

eager spindle
#

id say scene indices are about as "hard coded" as string names

rocky canyon
#

yea, im feeling that..

#

thats why i asked

eager spindle
#

you can always re-order your scenes by accident but your scene names wont change

rocky canyon
#

i need to use a cutscene now.. and id have to drop all these down a row

#

thats ridiculous

eager spindle
#

plus scene names are serialised like dictionaries anyw

#

i wonder if we can change scene directly based on a scene asset reference

rocky canyon
#

i probably could use an array instead

rocky canyon
eager spindle
#

i wish it were that way but because of legacy code it will not happen

rocky canyon
#

a list of scenes would be fine w/ me

eager spindle
#

scenes are built into the code

eternal needle
slender nymph
#

i just wrote a property drawer for a SceneAttribute that will draw a list of my scenes to choose from for a string variable. I think NaughtyAttributes probably has one of those as well

queen adder
#

Naughtyattributes

#

😏

wintry quarry
#

If it's a singleton you can just get the reference on demand

slender nymph
#

if you are trying to access the singleton, do it no sooner than in Start, especially if the singleton is initialized in Awake. you don't want the non-deterministic execution order of different objects to potentially fuck you over. but yeah you can also just access it on-demand rather than caching a reference to it in one of those initialization methods

#

rule of thumb is to do all self-initialization in Awake then wait until Start to access other components to ensure they are already properly initialized to the state you are expecting them to be in when you access them

outer coral
#

And then when worst comes to worst WaitUntil() they are initialized

mild onyx
#

so is there a way to swap a sprites texture? i figured that it would be less time consuming for me to duplicate my sprite and change the texture than to create a whole new sprite and manually add all the "rules" to it

swift crag
#

You can create a sprite object through code. That might be relevant.

#

I have not done that, though

lethal bolt
#

Why dosent this get the bullet prefab?

slender nymph
#

well for starters, a prefab does not live in the scene so it wouldn't find it with the tag since that only checks the scene

ivory bobcat
# lethal bolt Why dosent this get the bullet prefab?

The scene probably doesn't have a bullet object

This method returns the first GameObject it finds with the specified tag. If a scene contains multiple active GameObjects with the specified tag, there is no guarantee this method will return a specific GameObject.

slender nymph
#

and you can just drag the prefab into the slot in the inspector instead of using the Find call

lethal bolt
lethal bolt
slender nymph
#

prefabs can reference other prefabs

ivory bobcat
lethal bolt
#

Oh...

#

but ig i can just place the bullet prefab into the enemy. Lol.

#

Thanks!

lethal bolt
slender nymph
#

that means it was not assigned on whatever object you are using

ivory bobcat
#

You're probably referencing nothing

lethal bolt
#

oh because of the old code i removed the prefab........

slender nymph
#

ah yeah, if you didn't remove that line in Start then you're overwriting the inspector assignment with null

mild onyx
#

do scripts interfere with one and other or do they stay separate? in other words do they share variables?

swift crag
#

There are no "globals"

#

so x in one class will have nothing to do with x in another class

#

There are static members, which are part of the type itself, rather than part of a specific object.

#
public class Foo : MonoBehaviour {
  private static int counter;

  void Awake() {
    counter++;
    Debug.Log("This has run " + counter " + times");
  }
}
#

This will count up every time Awake runs

#

In this case, only Foo is allowed to see counter. If counter was public, then anyone could access it with Foo.counter.

mild onyx
#

i was going to use the y-axis number from my movement script for a platform in my game, like if Y > Y_of_platform dont allow pass through

#

guess ill have to check the characters coordinates in the platforms script

swift crag
#

If you need to be able to read a field from another object, you need to get a reference to it.

#

see the "Serialized references" section

peak ether
#

i need a push in the right direction, i understand c# well enough to get into trouble, heres what im trying to do, i have a "character" which at the moment is just a 2d square with collider, i want to click and hold then drag then release to launch the character in the opposite direction where force is how far back you moved your mouse, bonus points if someone can show me how to put a movement limit on the mouse so there isnt "infinite" force

rocky canyon
# peak ether i need a push in the right direction, i understand c# well enough to get into tr...

https://game.courses/mp - 2023 Multiplayer Mastery Course - Open NOW!
https://game.courses/birds - DOWNLOAD THE ART HERE
https://game.courses/bc - 2023 Game Programmer Course
https://prf.hn/l/BOo8AD1 - FREE Art from the Asset Store (Publisher of the Week)

Full tutorial to build a Unity game. Learn how to write code, deal with physics, sprites, ...

▶ Play video
#

check this out.. he basically does that exact thing

peak ether
#

ill check it out, thank you very much!

#

exactly what i was looking for ty

outer wigeon
#

Does anyone know how to enable text wrapping in an editor script for a TextArea? Is this even possible?

#

My reorderableList.drawElementCallback is kind of messy but I can provide it if necessary. The offending line is this one, I believe:

element.dialogueText = EditorGUI.TextArea(new Rect(rect.x, rect.y, rect.width, EditorGUIUtility.singleLineHeight * 3), element.dialogueText);
#

Or maybe something other than a TextArea would be better?

slender nymph
outer wigeon
fading seal
#

when the player interacts with the crate it is supposed to make a sound but it dosent here is the code and inspector ```cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class crateMoveScript : MonoBehaviour
{
public GameObject crate, crateText;
public AudioSource pickup;

void OnTriggerStay(Collider other){
    if(other.CompareTag("MainCamera")){
        crateText.SetActive(true);
        if(Input.GetKey(KeyCode.E)){
            crateText.SetActive(false);
            crate.SetActive(false);
            pickup.Play();
        }
    }
}
void OnTriggerExit(Collider other){
    if(other.CompareTag("MainCamera")){
        crateText.SetActive(false);
    }```
slender nymph
#

is the camera colliding with that object?

fading seal
slender nymph
#

ah, then that is likely due to you disabling the object that the AudioSource component is attached to

fading seal
#

ohh wait i didnt think about that lol

#

so ill make an empty game object with the sound that dosent get disabled?

slender bridge
#

Use an audio manager and pass the clip to it or deal with it all in the audio manager class

slender nymph
#

or just separate the audiosource from the part that gets disabled. or use the AudioSource.PlayClipAtPoint method

#

honestly though, the way you are handling interactions isn't exactly ideal in the first place anyway

fading seal
gusty lotus
#

I'm procedurally generating walls for a maze, and I'm trying to put materials on them but I don't know how to fix the stretched look of the wall materials

wintry quarry
#

or use a triplanar shader

#

or set the texture scale procedurally

gusty lotus
wintry quarry
#

what prefab are you instantiating

#

if it's a prefab, just set it up properly in the first place

gusty lotus
#

I have a wall prefab and I scale it to create the walls

#

it has a material on it

#

and when I scale the wall prefab the material looks stretched

wintry quarry
gusty lotus
#

okay thank you ill try that

remote osprey
#

What's the best way to add a Singleton to the project?

#

I created a property and an Empty GameObject with my singleton script and added it in the Inspector, but I'm not sure if there's a better way to do it

#

Didn't want to implement a threadsafe Singleton in C# so I had to go with Monobehaviour

remote osprey
slender nymph
#

if it is a MonoBehaviour then it has to be attached to a gameobject in some scene in order to actually be set up correctly

remote osprey
#

Tbh, I might not be on the level enough to understand this 😅

#

MAybe I should stick to keeping things in GameObjects

slender nymph
#

there's nothing really special or advanced happening here, it's just a property with an explicit backing field, it checks if that backing field is null when accessing the getter for the property, if the backing field is null is just creates a new gameobject using its constructor, then calls AddComponent. the only "high level" thing going on in the code i linked is that it is a generic class that I use for multiple singletons to inherit from. but if you just replace T in that code with the name of your class that you've turned into a singleton then it may make more sense to you

remote osprey
#

Oh, I see

#

I didn't know you could create game objects

slender nymph
#

yeah, new GameObject() just creates a new empty gameobject in the currently active scene

remote osprey
#

So I could just, maybe, copy your Singleton pattern and extend it into my Singleton classes? 👀

slender nymph
#

you could just copy that entire class and drop it into your project. then just inherit from SingletonBehaviour<YourClassType> instead of MonoBehaviour and you'll be good to go. however it's currently set up to only call DontDestroyOnLoad on it if you create it in the inspector and specifically assign true to that field

remote osprey
#

Cool feature!

#

Thanks for the help, pal!

eager wolf
#

this code is meant to load a scene, and then run a script in that scene called "MazeFloorManager"
But problem is that when i use this bit of script, it doesn't run the first time, but only the second time. What happens is that the first time it runs, the scene is loaded, and the second time, the next part of the script runs. I tried rmoving the "async" load but it doesn't change anything.

How can I load the scene and then immediately start using it?

primal aurora
#

if thats the case then add this to awake: DontDestroyOnLoad(this);

summer stump
flint python
#

Hello, when assign the option to dropdown in Start(), how can i change the label text? So, the text of that option is long, when that option is selected, I want to display a shorter text instead, not the entire string of that option. Thanks.

summer stump
eager wolf
#

thanks!

remote osprey
#

Should I leave my UI scripts as a canvas component?

#

Is there a rule for this kind of things?

#

I put mine inside a collider that is a child object of my canvas

rich adder
rich adder
remote osprey
#

Why wouldn't it be? 🤔

#

I need to do UI operations on it so I put a collider to detect clicks

rich adder
remote osprey
#

That was my reasoning lol

summer stump
#

You do not need a collider to detect clicks

summer stump
#

And ui should not have colliders

rich adder
#

collider is for physics, UI should not have physics

remote osprey
#

I'm not sure if I'm the worst Unity coder that's ever existed cause I keep making dumb stuff like this 🤣

rich adder
#

EventSystem is how you want to detect UI

#

inspector only solution they have EventTrigger, in code you can use the interface or the raycast from the event system itself

remote osprey
#

Interesting

remote osprey
#

I'll see to it once I unbreak my code 😃 👍

remote osprey
rich adder
remote osprey
#

Can I drag UI with this as well?

remote osprey
#

So I could drag my cards around

rich adder
remote osprey
#

Not sure if it's needed tho 😆

rich adder
#

the example goes hard on this one but you get the point lol

#

better more than less

remote osprey
#

Cool!

#

So I should just add the scripts directly to the Canvas then

rich adder
#

im not a fan of stuffing scripts in UI, ofc if its a runtime created UI element you have no choice also

remote osprey
#

I'm so scared of my entire code breaking after I make these changes 😆

#

Oh well

#

It's 10:00 PM

#

That's a problem for future me

rich adder
#

maybe practice on a separate smaller test project

#

before you convert, so you familiarize how it actually is working

remote osprey
#

Will do!

#

Thanks for the help!

iron wing
summer stump
#

Were you gonna.... say what you need help with?

#

Usually words are best, but ok

#

It depends on how you move, but you could do a second raycase angled forward, and check the dot product of the normal of the surface against Vector3.Up. if it is under a threashold, you can move up it, because the slope is gentle enough.
If over the threshold, just don't even allow movement in that direction

lusty fern
#

for a 2d game should i use 2d render pipeline or 2d universal

#

trying to make a game in 2 weeks with no coding experience

elder raptor
#

Something weird is happening, as you can see in the inspector, the value is 0
But when I debug the same variable, it debugs 1, any idea why?

nameText.text = "Qty x" + (UpgradesManager.Instance.largeTrucksOwned).ToString(); Debug.Log("Large " + UpgradesManager.Instance.largeTrucksOwned);

elder raptor
lusty fern
#

alr ty

wintry quarry
elder raptor
#

I think I figured it out FacePalm You were right, I did +1 to the other instance

#

I'm dumb

wintry quarry
#

Something is wrong

elder raptor
#

Yeah, I just added this too

if (Instance == null) { Instance = this; } else { Destroy(gameObject); }

#

I was testing something and forgot to delete that line 😭

wintry quarry
#

Ah, your Singleton implementation was not correct 👌

elder raptor
#

It was an issue that was happening when I was resetting everything, it was creating another instance.

#

Yeahh, I added it but commented it xD Forgot to uncomment it

violet glacier
#

How do you rotate a canvas ui image gameobject with recttransform? I'm currently in 2d

#

do I use .rotate or .localrotation or .rotation?

#

in these pictures, neither of the Z rotate is 90

wintry quarry
#

Your logs are printing the Quaternion

cinder mason
#

using unitys new input system, through code, how would i detect each scroll up or down, all i can find is how to get whether your currently scrolling up or down, but i want when you scroll one scroll wheel increment if that makes sense??

languid spire
faint lark
#

hey guys im trying to send some parameters through a string with animations but i get wrong format.

        for (int i = 0; i < _val.Length; i++) {
            print(_val[i]);
        }
        float _damage = float.Parse(_val[(int)AttackParameter.Damage]);
        float _knockback = float.Parse(_val[(int)AttackParameter.Knockback]);
#

specifically on _damage = and _knockback =

#

it prints the correct values

#

the values that i input are 1.0_1.0 etc.

rich adder
faint lark
#

not exactly

#

i assume turning a string into a float

#

so "1.0" wuld be a float of 1

languid spire
#

depending on your computer language/region setup you may need to use the Invarient culture for the parse

faint lark
#

im not aware of that

#

what is invarient culture

rich adder
faint lark
#

yes

#

1.0_1.0

#

and such

languid spire
#

well say your computer is set to Spanish.
Spanish uses , as the decimal seperator so 1.0 is invalid but 1,0 is correct.
InvarientCulture uses the US standard so 1.0 will always be correct on any computer

faint lark
#

but yes, after separation just 1.0

#

i see

#

how do i use this invarient culture?

languid spire
#

it is a parameter you can pass to float.Parse

faint lark
#

i cant see it

#

there are other parameters

languid spire
#

go read the docs

rich adder
#

it would be just be 10 no?

faint lark
#

is numberstyles.none the US one?

languid spire
distant relic
#

im working on a unity 3d game to run on google cardboard. when I run the game on my pc it works fine, but when i build and run on my phone the camera/player are in a different position

#

how can i fix this?

rich adder
distant relic
languid spire
# rich adder

what is your local culture. Is comma used as a thousands seperator?

rich adder
languid spire
faint lark
#

i figured it out

rich adder
#

would also try to be sure the values passed were even correct

var dmgVal = _val[(int)AttackParameter.Damage];
var knockVal = _val[(int)AttackParameter.Knockback];
Debug.Log($"dmg val: {dmgVal} knock val: {knockVal}");
float _damage = float.Parse(dmgVal);
float _knockback = float.Parse(knockVal);```
faint lark
#

i had to use system.globalisation

#

then it gave me the variables

#

also i used some wrong values 1.0f_1.0f

#

but i fixed it now and it works correctly

rich adder
#

you had f inside?

elder raptor
#

This code snippets works flawlessly on PC Build and WebGL Build but it causes the object to spasm out as if it got fits instead of clean rotation on mobile and this only happens when the object has to rotate, after the turning part is done and the object has to go straight, it goes normally:

Quaternion targetRotation = Quaternion.LookRotation(direction);
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, rotationSpeed * Time.deltaTime);
#

Maybe Due to Frame Rate differences or?

raw token
# elder raptor This code snippets works flawlessly on PC Build and WebGL Build but it causes th...

Seems fine enough... apart from lerping from the present value to the destination, which means that the interpolation will slow as it approaches the end value and will only approach the it as a limit rather than ever reaching it.

Framerate differences could see it visually leaping in rotation, but it shouldn't flip back and forth or anything.

If it's spasming out though, maybe your input value direction is changing erratically?

elder raptor
elder raptor
rich adder
#

just the t part is relevant

elder raptor
#

Okay it's working normally on Editor, lemme make a Mobile Build and check

rich adder
#

idk if that will fix your "spasm out" part, just fixes imprecision through diff framerates w lerp

elder raptor
#

Nope, didn't work. I guess it's not an issue with the rotation

#

Mute and watch, the music might be loud 😭

But yeah, this is happening. I think it's probably something to do with the waypoints breaking or something as it does continue on the path after doing that for a few seconds.

rich adder
#

maybe a video would help also

#

oh

elder raptor
#

Weird that it only happens on Mobile

elder raptor
rich adder
elder raptor
#

Yeahh

rich adder
#

can prob post the code to get better idea of what is going on

elder raptor
#

Okayyy

#

It's a mess as I had less than a day to make this whole game 😭

rich adder
#

those coroutines scare me a bit 😮

#

you might have conflicting runs going on

elder raptor
#

It was either that or update xD And I am scared of using Update

rich adder
#

coroutines are fine, but ideally you want to store them in vars to have more control of how many you run

#

or maybe stopping

elder raptor
elder raptor
#

So on mobile they don't run on different threads?

rich adder
#

I'm trying to look for bools but indeed you got a lot going on lol

elder raptor
#

I do have a lot of coroutines

raw token
elder raptor
#

Ohhh

rich adder
#

yeah they aren't true async/multithread

elder raptor
#

Ohh damn

#
 tr.gameObject.SetActive(true);
    tr.StartTrip();
    tr.outForDuty = true;
    idleTrucks.Remove(tr);
    trucksOutForDuty.Add(tr);

This is what I do when I send a truck out for a trip

#

And I have a separate list for Idle Trucks

#

Lemme just change the order and see

raw token
#

Do you know what the framerate on the mobile build is, out of curiosity?

elder raptor
#

Well, I use BlueStacks Simulator

#

Let's see if I can see the FPS there.
I did test on my sis' phone and it had the issue, that's when I started trying to fix it using Bluestacks

teal viper
#

It doesn't look like a performance issue to me

elder raptor
#

Yeah it isn't I capped FPS to 20 and it worked on PC

#

It's running on 59-60 on Bluestacks

#

I'll install Lunar Mobile Console and check logs ig

cyan folio
eternal falconBOT
elder raptor
#

It's weird that it's happening, cuz nothing seems wrong 😭

elder raptor
#

It happens on PC too now, I just noticed although it's very very rare Hmmmm

raw token
# elder raptor It happens on PC too now, I just noticed although it's very very rare Hmmmm

If that speed of 5.0f is accurate, at <50 fps, the truck could overshoot it's destination each frame and get stuck in a correction loop for a bit (but probably not indefinitely)... It would also exhibit at higher fps if the truck's y position differs from that of a waypoints', and if they ever differ by more than the 0.1 unit threshold the truck may never be able to reach the waypoint... But it doesn't sound like any of that is the source of the problem at hand :/

My only other thought is that it might somehow be trying to position itself towards two waypoints at once, like if two coroutines were competing... I don't see where that could be happening in the code, though. But in the video it sort of looks to me like the truck reaches it's first waypoint, and then the jittering begins as it turns towards it's next waypoint...

elder raptor
#

OHH

#

You might be right

#

Also is this odd for rotation?

#

I played the game frame by frame and notices the rotation value goes wild randomly

languid spire
elder raptor
#

The W in this, unsure what it is

languid spire
#

That is a Quaternion. the values are basically meaningless to most humans

elder raptor
#

Makes sense 😭

cyan folio
languid spire
elder raptor
#

Hmm I just noticed that it goes between negative and positive randomly when this happens. I had to screen record and view the video frame by frame 😭

cyan folio
elder raptor
languid spire
atomic yew
#

I'm making a game in Unity and there are vendors in my game and when I click on these vendors, the UI panel opens. This ui panel raycast target option is active but can still click on the seller behind it. With some sellers it doesn't click as I would like, but with others it does. How can I solve this problem?

languid spire
cyan folio
elder raptor
# languid spire that looks like a problem with your Direction calculation. Are you reading and a...

Only this

float smoothingFactor = 0.1f;
Quaternion targetRotation = Quaternion.LookRotation(direction);
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, 1 - Mathf.Pow(smoothingFactor, Time.deltaTime));

for rotation and then this for snapping them to right rotation when they stop:

if (transform.forward.z > 0.0f)
{
    transform.rotation = Quaternion.Euler(0, 0, 0);
}
else
{
    transform.rotation = Quaternion.Euler(0, 180, 0);
}
languid spire
elder raptor
elder raptor
cyan folio
languid spire
elder raptor
# languid spire what, exactly is this Debug showing?

The Direction Vector and the Current Targetting Waypoint from the code snippet that handles the position and rotation:

Vector3 direction = (targetPosition - transform.position).normalized;
Debug.Log("Direction: " + direction + " And Waypoint: " + waypoint);
transform.position += direction * speed * Time.deltaTime;

float smoothingFactor = 0.1f;
Quaternion targetRotation = Quaternion.LookRotation(direction);
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, 1 - Mathf.Pow(smoothingFactor, Time.deltaTime));
languid spire
elder raptor
#

There's no change in the targetPosition or the transform.position, only the Direction Vector.

raw token
# elder raptor

I think that looks like the shooting and overcorrecting - it's ending up more than 0.1 units away from targetPosition each frame. You might clamp the change in position to the distance to targetPosition

languid spire
# elder raptor

Indeed. remove the .nomalize from direction. it's not needed anyway

raw token
#

Or that - that's better 😁

elder raptor
languid spire
elder raptor
#

Wrong video wait

glossy turtle
elder raptor
languid spire
# elder raptor

I have no idea what is going on there but those direction vectors make no sense based on the positions used

elder raptor
#

Yeah, it's weird. This issue randomly started, didn't have it before

cyan folio
languid spire
#

the only thing it can be is this

transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, 1 - Mathf.Pow(smoothingFactor, Time.deltaTime));

it must be overcompensating

raw token
# elder raptor Yeah, it's weird. This issue randomly started, didn't have it before

How about

        Vector3 targetPosition = new Vector3(waypoint.position.x, transform.position.y, waypoint.position.z);
        float distance;
        while ((distance = Vector3.Distance(transform.position, targetPosition)) > 0.1f)
        {
            Vector3 direction = (targetPosition - transform.position).normalized;
            transform.position += Vector3.ClampMagnitude(direction * speed * Time.deltaTime, distance);

            float smoothingFactor = 0.1f;
            Quaternion targetRotation = Quaternion.LookRotation(direction);
            transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, 1 - Mathf.Pow(smoothingFactor, Time.deltaTime));

            yield return null;
        }
elder raptor
glossy turtle
#

there is an animator window. you have to add speed which you mentioned.

elder raptor
#

It didn't happen

#

Let me make a mobile build and check

glossy turtle
#

instead of two translates put one.

cyan folio
glossy turtle
#

moveDirection = new Vector3(horizontal, 0, vertical).normalized;

    transform.Translate(moveDirection * Time.deltaTime * speed, Space.World);
#

first of all you are checking vector3.zero and you are using ! so how you are altering speed.

elder raptor
#

Thank you too Steve!

cyan folio
raw token
elder raptor
#

Yeahh, Unity engine do be weird.

glossy turtle
languid spire
raw token
#

@elder raptor is speed set to to something other than 5.0 in the component inspector, out of curiosity?

elder raptor
cyan folio
glossy turtle
cyan folio
raw token
# elder raptor Yeah, it's double

ah that'd be it... At 60 fps the truck would move ~.167 units per frame, so it'd have a hard time hitting that 0.1 units to targetPosition threshold 👍

Edit: though on second thought, 0.1 would be radius... It'd have to get within a 0.2 unit circle... so I still dunno 😕

topaz fractal
#

public class newPlayerScript : MonoBehaviour
{
    [SerializeField] Transform cameraProp;
    [SerializeField] float sensitivity = 100f;
    Vector2 look;

    void Start()
    {
        Cursor.lockState = CursorLockMode.Locked;
    }


    void Update()
    {
        look.x += Input.GetAxis("Mouse X") * sensitivity * Time.deltaTime;
        look.y += Input.GetAxis("Mouse Y") * sensitivity * Time.deltaTime;

        cameraProp.localRotation = Quaternion.Euler(-look.y, 0, 0);
        transform.localRotation = Quaternion.Euler(0, look.x, 0);
    }
}
``` theres no reason that this shouldnt move my camera up and down, i have the camera attached in unity, its only one button
elder raptor
glossy turtle
elder raptor
topaz fractal
#

its the child of my player object

cyan folio
topaz fractal
elder raptor
#

Weird, lemme try

topaz fractal
#

thanks man

#

@elder raptor any luck

elder raptor
elder raptor
# topaz fractal <@277120840150024192> any luck

Don't use two cameraprop.localRotations for each rotation, use this instead:

cameraProp.localRotation = Quaternion.Euler(-look.y, look.x, 0);

And if you saw, you did transform.localrotation for the second one xD So that might've been an issue too.

topaz fractal
#

what should i have put instead?

elder raptor
#

And if you're attaching the script to the camera itself, you can do Camera.main or just do cameraProp = this;

elder raptor
#
void Update()
    {
        look.x += Input.GetAxis("Mouse X") * sensitivity * Time.deltaTime;
        look.y += Input.GetAxis("Mouse Y") * sensitivity * Time.deltaTime;

        cameraProp.localRotation = Quaternion.Euler(-look.y, look.x, 0);
    }
#

This will be your update then.

topaz fractal
#

this video confused me

#

watch it real quick @elder raptor

elder raptor
#

He was rotating the player sideways instead of only the camera

#

And only the camera for Vertical Moving

cyan folio
topaz fractal
#

aha there we go

elder raptor
#

That's better if you're making a First Person Controller.

So use the code you wrote and attach it to the Player Object instead of the Camera and then attach the camera reference to it.

topaz fractal
#

that was my mistake

#

yeah ive done that

elder raptor
#

Okay good good

topaz fractal
#

wonder how i missed it

#

thanks man

elder raptor
#

No problem

regal basalt
#

Good morning, i am using couple scripts for player movement and for the player camera, but they don't actually work. Is there a way to solve it?

Also the player movement's "rigidbody" flies away towards Z axis

elder raptor
elder raptor
#

xD

regal basalt
elder raptor
#

Did you attach the script to a gameobject?

regal basalt
elder raptor
#

And sharing your code(s) would help

regal basalt
#

the movement has a gameobject with the script and rigidbody

languid spire
eternal falconBOT
elder raptor
#

And always use proper debugs to figure out the issue first. ||I know I don't do that all the time but it is worth following xD||

In your case, you can add debugs to the Input.GetKey/GetKeyDown statements to see if the key clicks get register. If they do, then you can see if the movement functions get properly called, etc.

regal basalt
# elder raptor And sharing your code(s) would help
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    public float moveSpeed = 5f;
    private Rigidbody rb;

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

    void FixedUpdate()
    {
        Move();
    }

    void Move()
    {
        float moveX = Input.GetAxis("Horizontal");
        float moveZ = Input.GetAxis("Vertical");

        Vector3 moveDirection = transform.right * moveX + transform.forward * moveZ;
        rb.MovePosition(rb.position + moveDirection * moveSpeed * Time.fixedDeltaTime);
    }
}
languid spire
#

Ok, so you should read Input in Update and consume it in FixedUpdate

regal basalt
#
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    public float moveSpeed = 5f;
    private Rigidbody rb;

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

    void FixedUpdate()
    {
        Move();
    }

    void Move()
    {
        float moveX = Input.GetAxis("Horizontal");
        float moveZ = Input.GetAxis("Vertical");

        Vector3 moveDirection = transform.right * moveX + transform.forward * moveZ;
        rb.MovePosition(rb.position + moveDirection * moveSpeed * Time.fixedDeltaTime);
    }
}
elder raptor
#

And can you also show the Rigidbody settings?

Also, the firs thing to try is to increase movespeed all the time, sometimes it does move but like one pixel per frame

regal basalt
elder raptor
regal basalt
# languid spire Ok, so you should read Input in Update and consume it in FixedUpdate
    //like this?
void Update()
    {
        // Capture input in Update
        moveX = Input.GetAxis("Horizontal");
        moveZ = Input.GetAxis("Vertical");
        mouseX = Input.GetAxis("Mouse X") * mouseSensitivity;
        mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity;

        // Rotate camera in Update for smoothness
        LookAround();
    }

    void FixedUpdate()
    {
        // Consume input in FixedUpdate
        Move();
    }
cyan folio
#

@glossy turtle Are you still here?

regal basalt
elder raptor
fickle plume
cobalt sentinel
#

How can i do when it isn't touching it, the variables become true again?

#

sorry if my english is bad

cobalt sentinel
#

thanks

regal basalt
#

the input is all set as well

elder raptor
elder raptor
#

Yeah the movement script

regal basalt
#

alrght

#

will i need to set a rigidbody in the parent?

elder raptor
#

Yes

#

Remove it from the child, I usually make an Empty Game Object called Player that has the collider and rigidbody and Player mOvement script then make the Player Model the child of it.

regal basalt
#

i just did it

regal basalt
#

so, the movement is fixed and working, but now i will need the camera to be in the right position

#

    //For the camera i'm using this script
public class CameraController : MonoBehaviour {

    public float mouseSensitivity = 2f;
    public Transform playerBody;

    private float verticalLookRotation = 0f;

    void Start()
    {
        Cursor.lockState = CursorLockMode.Locked;
    }

    void Update()
    {
        LookAround();
    }

    void LookAround()
    {
        float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity;
        float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity;

        playerBody.Rotate(Vector3.up * mouseX);

        verticalLookRotation -= mouseY;
        verticalLookRotation = Mathf.Clamp(verticalLookRotation, -90f, 90f);

        transform.localEulerAngles = Vector3.right * verticalLookRotation;
    }
}
tight laurel
#

Ive heard it can be a good idea to go read someone elses code for a game, is there a game that is easy to understand of which you would suggest to check out if someone wanted to see how the coding is actually put into effect? Ive considered Hollow Knight but i dont know how to access its code

regal basalt
#

@elder raptor thanks for the help, i'm going to keep up with the animations

final kestrel
#
   private ItemDatabaseObject database;

   private void OnEnable()
   {
#if UNITY_EDITOR
       database = (ItemDatabaseObject)AssetDatabase.LoadAssetAtPath("Assets/Resources/Database.asset)",
           typeof(ItemDatabaseObject));
       Debug.Log(database);
#else
       database = Resources.Load<ItemDatabaseObject>("Database");
#endif
   }

the database returns null. Why is that?

warm garden
final kestrel
regal basalt
elder raptor
regal basalt
#

but now i want to change between the main camera and the player camera, is there an easy way to do it?

elder raptor
#

ex

camera1.setActive("false");
camera2.setActive("true")';
#

Even better, if you can get reference of the camera as a Camera data type, you can just do .enabled = true/false.

public Camera camera1;
public Camera camera2;

void Switchcams()
{
camera1.enabled = false;
camera2.enabled = true;
}
regal basalt
#

for example, do i create a script for the cameras and put it in both cameras?

elder raptor
#

Make a script called CameraManager with a function to switch the cameras

regal basalt
#

like "switch cameras"

elder raptor
#

And attach it to an Empty Game Object named Managers or Camera Manager or something

#

Technically you can do it in your Camera Controller script but it's not neat xD

regal basalt
#

i did that code 4x before it even work

elder raptor
languid spire
regal basalt
elder raptor
regal basalt
elder raptor
#

It's obviously best not to have messy code and use AI generated snippets that you don't understand.

regal basalt
#

i organize my code