#💻┃code-beginner

1 messages · Page 507 of 1

rustic maple
#

gotcha

wintry quarry
#

Well there arre certainly people in the comments with the same issue

polar acorn
#

Timestamp? This is a very long video, where does that code get added?

rustic maple
#

8:15

rancid tinsel
#

im very concerned by the angry face at the end of the error

polar acorn
rustic maple
#

oh wait i see at 8:36 it shows

rancid tinsel
#

not bigger than XD

polar acorn
#

Where?

languid spire
wintry quarry
rancid tinsel
rustic maple
languid spire
#

i guess you fucked up

polar acorn
rancid tinsel
wintry quarry
rancid tinsel
#

but i changed it to != now

polar acorn
rancid tinsel
#

that doesnt look right even to my eyes

rustic maple
wintry quarry
#

which it can't ever be null anyway because it's an int

polar acorn
#

It doesn't call SetDestination on it

languid spire
#

@rancid tinsel And please learn to cache your GetComponents

wintry quarry
#

in short - the tutorial is poorly made!

rustic maple
#

jup

polar acorn
rustic maple
#

but my ai works now!

rancid tinsel
languid spire
rancid tinsel
#

yeah just laziness

languid spire
#

bad habit to get into, break it asap

rancid tinsel
#

youre right

#

ill tidy it up right after i fix the bug

#

to double check by caching you mean making an instance and then changing that instance?

#

so this kind of thing?

languid spire
#

no, just calling GetComponent once (if you must) and save a reference then use that reference

languid spire
#

Also look at how many times you are doing the same Mathf.Abs, you only need to do it once for each axis

arctic ridge
#

How can I make a line cast 2D hit every layer except for one? I know there is a layer mask included, but doesn’t that make it so it only hits objects on that layer?

wintry quarry
#

in the dropdown you can select all the layers except the one you want to exclude

#
public LayerMask mask;``` you can configure it in the inspector
arctic ridge
#

Ooh thanks!

near wadi
#

I am using GetComponentsInChildren. is there a way to limit the hierarchy levels? i mean, i only want the immediate children, not all the levels

languid spire
near wadi
drifting onyx
#

How would i make this work so that it uses the prefab I've slotted into here. Whenever the code on the script is run It hits me with the "The Object you want to instantiate is null"

#

script isnt on an object until runtime

polar acorn
# drifting onyx

The default values will only apply to new instances of this script added in Edit mode. It won't affect anything already in the scene, or instances of this script created at runtime

drifting onyx
#

any reccomendation on how I would do this then? The way i've been doing it wont work since ths cript isnt on anyhthing until runtime

polar acorn
#

You'll need to get the reference after the object exists. Either pass it in from another object that's in the scene before play mode starts, or load the prefab from Resources

languid spire
#

move the prefab to a Resources folder then use Resources.Load in the Awake of the script

hollow field
#

Hey, I'm having an issue with speed (not the drug). I have ```cs
public float speed = 15.0f;

steep rose
#

are you changing it in game? if so unity does not save changes that way

wintry quarry
#

or you're looking at the wrong inspector

languid spire
#

or changing it in Play mode

hollow field
#

not after pressing play/pause

steep rose
#

then most likely what Praetor said

hollow field
#

I have a bit that sets it to 0 at some points but that bit of code isnt being run during the issue

eternal falconBOT
polar acorn
hollow field
#

(please forgive the horrible code)

polar acorn
#

That would mean a different script is changing it

steep rose
#

also are you manually changing the rigidbodies transform?

hollow field
#

yep got it

#

I have a World Object with a world script where I instantiate the player and have ```cs
public float _playerSpeed = 15.0f;

if (gameRunning == true)
{
player_script.speed = _playerSpeed;
}```

hollow field
tepid summit
#

If i were to try and delete a clone of a gameobject, how would i make sure it only destroys the clone and not the prefab?

eternal needle
tepid summit
#

yeah but it still gives an nre

eternal needle
#

Then you have a NRE issue which is entirely different from what you initially asked

tepid summit
#

my bad

#

how would one prevent that nre issue

eternal needle
tepid summit
#

would you like my script rq

eternal needle
tepid summit
#

im just not so sure about the null logic

polar acorn
tepid summit
#

ive taken a hiatus from unity so im a little rusty

eternal needle
tepid summit
#

hold up

#

what if instead of Destroy(this.gameObject), i do:
Destroy (clone.Object)

#

i named the object clone btw

#

Similar to this:

#
clone.velocity = transform.TransformDirection(Vector3(0,0, speed));
Destroy (clone.gameObject, 3);```
mortal spade
#

anyone have a quick way to pick between two numbers that arent sequentially next to each other? i wanna pick between indice 12 and 14 but obviously i cant just use Random.Range cuz itll include 13 as well

tepid summit
mortal spade
#

ah ok that should work

#

ty

tepid summit
#

all g

keen dew
#

That will pick one of them twice as often

#

12 + Random.Range(0, 2) * 2

#

Random.value > 0.5 ? 12 : 14

mortal spade
#

ooo oky

#

i did just notice that 😭 ty as well

tepid summit
#

at least i tried my darndest

mortal spade
#

yea !!

tepid summit
#

ye

tepid summit
#

i have fixed the nre

#

yet, another issue rises

#

now when i create this object it has no force behind it even though i scripted it to.

#
    {
        
        GameObject NewShot = Instantiate(Shot, BowFirePos.transform.position, Player.transform.rotation);
        ShotPhys.velocity = transform.TransformDirection(Vector3.forward * 25 * Time.deltaTime);
        Destroy(NewShot.gameObject, 5);
        yield return new WaitForSecondsRealtime(8);
    }```
#

P.S i have tried putting the velocity line in the update as well and nothing changed

tepid summit
#

Also just tried changing the line to
Shot.GetComponent<Rigidbody>().velocity = transform.TransformDirection(Vector3.forward * 25 * Time.deltaTime);

#

hold up, got an idea

#

yeap

#

fixed it, sorry for filling up chat

polar acorn
tepid summit
#

a rb

#

but i fixed it

somber herald
#

What's the difference between Vector3.magnitude and Vector3.distance

#

i mean taking two vector3s and calculating the magnitude difference

tepid summit
#

adding them and subtracting the smaller one doesnt sound wrong to me

#

however,

#

i do not do magnitude and difference calculations

polar acorn
#

Distance requires two points. Magnitude is just one point.

somber herald
#

oo okay

tepid summit
#

ah gotcha

stuck monolith
#

hi all it bend stuck on for the last 25 hores pls help

#

@polar acorn

polar acorn
stuck monolith
#

up adve it

#

taht why

polar acorn
#

I have no idea what you are saying

stuck monolith
#

hi all it bend stuck on for the last 25 hores pls help

arctic ridge
#

I'm trying to make an enemy AI that jumps if there is an object between it and the player. To do this, i am using a line cast to check if the line is broken before it reaches the player. Unfortunatley, it does not work right now, and im not sure why. If someone could explain the issue, that would be great! https://paste.ofcode.org/F2U3r6TtfGfRUqxPMXdpFx

wintry quarry
#

You need to pick one and stick to it.

arctic ridge
wintry quarry
#

The linecast logic is also definitely off. Partially what digi said and partially just - it doesn't make much sense at all

#

what's with (player.position.x * 3)

arctic ridge
wintry quarry
#

Also this code:

            Vector2 Stop = new Vector2(0,0);
            rb.AddForce(Stop);```
does absolutely nothing
#

adding zero force is just that

#

doing nothing

polar acorn
#

"Hey man what's your address?"
"West"

arctic ridge
#

Fair point

arctic ridge
arctic ridge
polar acorn
arctic ridge
#

Yeah, i was trying to make it so the linecast went towards the player but looking at it now that seems redundant huh

wintry quarry
#

You would just do Linecast(enemyPos, playerPos)

#

that's it

arctic ridge
#

Yeah i see that now for sure

unique canyon
slender nymph
#
  1. not a code question. #🏃┃animation
  2. you need to select the object you want to animate and you probably need to also add the sprite property to control it
unique canyon
queen adder
#

the toggle ui isnt working

#

its not letting me click it

deft grail
queen adder
#

a ui toggle

#

im tryna click it

#

and its not toggling

deft grail
#

idk what your trying to click so its hard to help

queen adder
#

one of these

#

im tryna click the toggle checkbx

#

and its not changing

deft grail
queen adder
#

yes

#

sliders work

#

but not the clcikers

deft grail
queen adder
#

no idont think so

glossy turtle
queen adder
#

in play mode

glossy turtle
#

I am not understanding what are you trying to do and what is not happening.

queen adder
#

the toggler aint toggling

night lance
#

hi! i have an issue where i can't set the .cull of CanvasRenderer's using booleans! it works when i do !textRenderer.cull to flip it but refuses to take bool input

wintry quarry
#

Can you show your exact code and the error(s) you're getting?>

night lance
#

its not throwing errors unfortunately

#

these functions are being called through unity's event system fyi

wintry quarry
#

Add some Debug,Log, but there's no reason that wouldn';t work

#

you're probably passing in the wrong value (true or false)

#

or something like that

night lance
#

also when adding either of them to my awake or start functions, things are weird ~ only one of the canvasRenderer's has anything happen

glossy turtle
#

There is a script attached to your toggle did you wrote anything not to toggle in update method.

queen adder
#

no

night lance
#

(and i have passed true and false via a checkbox in the unity inspector)

wintry quarry
night lance
#

... value?

#

where is the value param? /gq

#

(meaning the active boolean? that seemed to be working fine)

glossy turtle
#

Did you tried dynamic bool option.

queen adder
#

im finding the new input system difficult to work with, should i go back to the old input system?

night lance
timber tide
#

(new) input system isn't a requirement and for smaller projects I wouldn't suggest putting too much time into it

glossy turtle
night lance
#

ok!

polar acorn
glad comet
#

!code

eternal falconBOT
glad comet
#

I keep getting this error and I can't figure out why

#

error CS0246: The type or namespace name 'boxCollider2D' could not be found (are you missing a using directive or an assembly reference?)

#

I thought that I referenced boxCollider2D in the first few lines my code

deft grail
#

your trying to check a boxCollider2D

#

as a type

#

but a. that doesnt exist
b. im not sure if you can use something other than the one premade with OnTriggerEnter

glad comet
#

I think maybe I dont understand the OnTriggerEnter

#

now i get this error

#

(27,32): error CS1061: 'Collider' does not contain a definition for 'boxColider2D' and no accessible extension method 'boxColider2D' accepting a first argument of type 'Collider' could be found (are you missing a using directive or an assembly reference?)

polar acorn
sly lintel
#

its not even running, but if hasDone = false it should be running that first if statement on awake?

polar acorn
arctic ridge
#

Using the method input.GetButtonDown("Fire3") is called under two different buttons between my laptop (mac) and PC(windows). Is there any specific cause for this? Movement is also different between the two, assumendly because its placed under void update and not fixed update

deft grail
sly lintel
polar acorn
# sly lintel

Whenever this object is first activated, it will run the first part of the if condition.

#

Is this object active in the scene?

sly lintel
#

to explain, it is a warning screen that I only want to show once, when you die in the game the scene is reset and I was trying to find a way to not show the loading screen after dying again

#

so my thought process was to setActive on awake

polar acorn
arctic ridge
#

Yeah they’re both mapped to joystick button 2 (I’m using controller for this), but they’re two different controllers

sly lintel
#

you are right this totally makes no sense Awake does not save that when reloading a scene

#

do you have any idea a work around for this or do i need to rework how i reset scenes?

polar acorn
#

You will need something that persists between scenes, either a static variable or a DontDestroyOnLoad object

queen adder
#

ive made this melee attack and implemented a script that allows it to play on a button press, which works. the issue is it only works once, i cant make an attack after the first time i do so, i dont think its a scripting error i think its an animation one but im unsure

glad comet
#

Thank you for helping solve the OnTriggerEnter issue

#

but I was trying to solve this issue so that this code would stop the gameobject it's attatched to if it hits an object with the tag "player"

polar acorn
deft grail
glad comet
polar acorn
polar acorn
#

Which means Unity won't call it

glad comet
#

typo

glad comet
#

thank you

queen adder
#

How do initiate download from game made with unity ? For example, in android web browser initiate a download and the file is saved in download folder, i want to do the same with my game

queen adder
#

And how do i get the path to download folder ?

wintry quarry
#

you don't "get" it

#

you provide it

queen adder
#

I dont understand

#

File.writeallbytes require file path

wintry quarry
#

yes you can put whatever file path you want

queen adder
#

And it will be saved in download folder regardless of what the filepath is ?

wintry quarry
#

no...

#

it will be saved in whatever path you give it

queen adder
#

But what if i want to allow the download to be managed by external download manager instead ?

wintry quarry
#

what does "external download manager" mean

wintry quarry
#

You would need to use native android Java code for that

queen adder
#

i want my download to be handled by download manager as well

wintry quarry
#

I just explained it to you

#

Assuming you're talking about Android

queen adder
wintry quarry
#

so it depends on the platform

queen adder
#

Ah okay, thanks

#

So no built in way in unity to do it and i must use platform specific way right ?

wintry quarry
#

yes

queen adder
#

Okay thanks

night lance
# polar acorn Show where you are calling this

hi! sorry for the late response: its through a UnityEvent handled in a silly way: its added to a player's unityevent and the way that gets invoked is on keypress through unity's input system

polar acorn
queen adder
#

How do i check if assetbundle is a scene without loading it ? for security reason I want to allow loading assetbundle except those that contain scene

#

The reason is because scene can contain script placement in object which is dangerous

tame valley
#

the variables are still assigned during runtime

tiny rain
#

Disabling reload domain means that when running the game, several things happens, including that no static variable will be cleared nor assigned

#

Easy way to check if that's the culprit is try trigger a recompilation, by modifying your code somewhere or something alike, and then look if the first time runs correctly

tame valley
#

i have only 1 function using static but i use the method on unity so it work when not reload domain

#

is it the right way to solve static issue when disable reload domain?

keen dew
#

The right way to solve it is to enable domain reload

tiny rain
#

I think that he might've disabled it for the same reason as mine- Waiting time

tame valley
tiny rain
#

It's annoying to wait for reload whenever I run it

keen dew
#

These kinds of issues are inevitable with it so you'll have to choose

tiny rain
#

It's not exactly inevitable

tame valley
#

questions: will disable reload domain cause effect on instantiate prefabs?

tiny rain
#

I made complex systems with it disabled, you just have to be careful with what you do, and understand what gets executed only upon recompilation and what does not

#

Nope?

tame valley
#

damn i have no clue

tiny rain
#

I think that runtimeInitializeOnLoad might only execute once across multiple plays though

#

Probably is the case

#

Basically that function will only be ran when you trigger a recompilation or so

#

It's hard to track down exactly what happened, though, without testing a bunch of things or walking through with a debugger

tame valley
#

so when i start, it initialize this function once, to reset all data, the initialize works fine, but when i start invoke the function again during the playtest, the issue occur

tiny rain
#

Looks like this is per inventory slot?

tame valley
#

yea it is

tiny rain
#

Welll... Awake, Start, Update calls would still happen perfectly normally on monobehaviours, no matter domain reload or not

tame valley
#

ok i triple checked everything, and im like 99% sure the issue was in this static

#

is there anyway to disable domain, but still able to run this static normally?

tiny rain
#

Hmmmm... Lemme think...

#

I'm pretty sure that the attribute on the method only runs on domain reload...

#

new InventoryItem looks like it could totally be a constructor

tame valley
tiny rain
#

Personally. I'd say that you might as well make it:
public static InventoryItem empty = new InventoryItem(null, 0) or new InventoryItem(), if you don't need to assign anything

referenced by InventoryItem.empty

tame valley
#

the full struct of the inventory item

tiny rain
#

Quantity is 0 by default, and item is null be default, normally, so you can drop the item = null and quantity = 0

#

Not sure how the IsEmpty'd run tbh, I gotta test some things

#
public struct Itemstack
{
    public Sprite icon;
    public int amount;

    public static Itemstack empty = new Itemstack();
    public static Itemstack empty2 = new Itemstack(){ icon = null, amount = 1 };
}
#

This runs just fine

tame valley
#

it said that the parentless struct constructor isnt avalable in C# 9.0 ...

tiny rain
#

Cus references are null be default, and any number variable are 0 be default

tame valley
#

hmm thats fair

tame valley
tiny rain
#

Also, yeah, lacking support for parameterless constructors is a big pain in my neck at times, as sometimes I'd like to just follow normal conventions but make sure that some initialization is always done, but then that comes in xD

tiny rain
#

As long as you don't modify it, which I doubt you will

#

Const in C# is a hassle too for me '^^

tame valley
#

but i though that it still have static in the line? :\

tiny rain
#

Even though it makes sense for it to be a const

tiny rain
#

Well, honestly you'd best test and read about it, I'm no expert, I just dealt with it quite a lot since I hardly ever keep domain reloading on

#

Essentially only domain reload will assign the function's initial value again, so without it, it wouldn't revert to null/whatever the default value is upon pressing play

#

However, domain reload or not, the static variable will never automatically revert to it's initial value upon transitioning scenes, it's important to keep that in mind

tame valley
#

ok it still didnt work, thanks for your help though, maybe i will try to ask someone for a full check because im not capable of doing this XD

tiny rain
#

Mistake on my part: RuntimeInitializeOnLoad is an attribute that causes a method to execute whenever you start playing

#

Imma just dig into this a bit more myself, since I figured that I don't know this static stuff well enough, bye

#

No problem

astral falcon
#

What was the initial issue again?

tiny rain
#

Sounds like a typical static variable issue in my opinion

astral falcon
#

on what line was the issue?

astral falcon
#

Phew, is the code somewhere readable? 😄 @tame valley

tiny rain
#

That line references an image... Uh, actually, this issue doesn't make much sense now that I think about it, it's likely something assigned in the inspector?

tame valley
#

if you interested in helping, i could give you my current scripts, its not long, but idk how to upload all of it for you to check? ToT

astral falcon
#

!code

eternal falconBOT
tiny rain
#

Well, anyway, Imma be off then, cya guys

tame valley
#

bye, gn

astral falcon
#

when the error occurs, what is the serializedfield looking like? is itemImage actually empty in the inspector?

tame valley
#

i checked, the inspector still have all variables assigned

astral falcon
#

Of the created object in the scene hierarchy?

tame valley
astral falcon
#

Pretty sure? You should check right now 😄 run the app and see when the errors occur, click on the error, it might highlight the object its crying about or you just debug log the gameobject before you enable the itemImage, so you know its name

tame valley
#

the first time i ran after reload domain, it works as intented, but the second time when i dont reload the domain, the issues occur

astral falcon
tame valley
#

ive do all the debug.log

astral falcon
#

and after that, you are just starting playmode without reloading?

languid spire
tame valley
#

so when i save my file from editing, the domain automatically reloaded, so i get the first run successfully, but in project settings i set reload domain to be disabled , for faster play, and the error appears

astral falcon
#

Id say, you are creating objects on the first playmode and when exiting, they get destroyed, but as you do not reload anything, it will just keep the created objects and try to access them, which turned null on exiting playmode.

tame valley
astral falcon
#

ondisable usually

languid spire
astral falcon
#

you could also double check your created lists count. I guess, it adds up on the second play run when not reloading

tame valley
#

the 2nd time i run. ItemList still have the same count which is 33

astral falcon
#

When the error is happening, what is calling the ResetData method?

#

Oh wait,you are calling it in awake?

tame valley
#

Awake was when i first launched, all the item slots are create and reset to the empty state

#

believe it or not, the resetData actually work the first time when it run, and after that when i invoke the ResetData function again, it crashed

#

do you want the full project im currently doing for a deep test, if you got time?

astral falcon
#

Nah sorry, got my own hassle with visionos here 😄

tame valley
#

yea fair enough

astral falcon
#

but you are subscribing the oninventoryupdated function, which is the start of the whole script execution. And never remove the event subscription. I would remove the image.enabled line and debug.log the gameobject, maybe give it a unique name if image == null and check again in the project hierarchy.

tame valley
#

ok lemme go through and do all the unsubcribe thing.

late pasture
#

MissingReferenceException: The object of type ‘Image’ has been destroyed but you are still trying to access it.

#

you are trying to access it somewhere in your code, after destroying it

languid spire
#

which points to not unsubscribed events more often than not

astral falcon
#

I am just wondering, why its calling the image to be destroyed but not the whole UI_Item holding it and therefore firing a null error upfront

tame valley
#

OHMYGOD IT WORKED

#

i unsubcribe everything. it worked

#

thanks so much @languid spire @astral falcon

astral falcon
#

welcome to delegates, events and other subscription fun 😄

tame valley
#

arggggggggggggggggggggggggg

#

GOD DAMN IM SO STUPID

languid spire
#

Always, always, always unsubscribe. Lesson learned I hope

tame valley
#

LESSON LEARNED

astral falcon
#

We all been running into this at some point 😄

tame valley
#

ARUGHGHGHGHGHGH

#

i swear this took me like 8-9 hours to debug this crap

#

once again, thanks so much, im so happy rn

queen adder
#

How do i mark folder/file as being used ?(for example, if user try to delete a file that is being used by app, windows will throw error that it cant delete the file because it is being used)

keen dew
#

Depends how you open the file, but generally you should open it with a using statement so that it's automatically closed when you're done with it

queen adder
keen dew
#

google for "lock folder c# windows"

queen adder
#

Ok thanks

foggy saffron
#

Not sure what I'm missing here. The script has no compile errors and it looks like the name is the same as the class name.

slender nymph
#

do you have any compile errors? even ones you think are unrelated to this component?

foggy saffron
#

Not that I have seen. Or at least non showing on the console. I just fixed a bunch of them.

#

looks like its just messages saying the referenced script is missing

slender nymph
#

clear the console and see if any appear

foggy saffron
#

Yeah still no red errors in it.

#

and the project will run.

slender nymph
#

then change something in the code, save, and make it recompile then try adding the component again

foggy saffron
#

still nothing

slender nymph
#

screenshot your entire console window

foggy saffron
#

only the 2 things in it atm

slender nymph
#

at the very least you should fix those warnings. if the issue persists then try restarting the editor

foggy saffron
#

werd. I didn't think those would keep me from attaching a script so I thought I'd try.

night valve
#

Had similar issue, turned out to be just some old duplicated script with different class name but the same filename or something. Don't remember for sure, but I'd suggest double checking for duplicates

foggy saffron
#

will do. Thanks for the input.

lone sable
#

If I wanted to do a seeded run in my game. Whats the proper way to handle it? The way I was handling it before, seems to be wrong at this point.

My General Thought is: Everytime I do an action. EG: Open a chest, Spawn in something "Random" or Load a random level I need to store the seedstate.

However, if a player say, skips opening that chest. Because of how I have it coded right now, not opening that chest will force the next room to be different, because opening that chest effects the seeded state.

Just wondering if theres another way to go about this before I start digging into running the random generation when the chest spawns instead etc.

slender nymph
#

use the seed to make those decisions without the player being required to interact with the objects to do so

errant quiver
#

Hello

I got this error "NullReferenceException: SerializedObject of SerializedProperty has been Disposed." after the exit play mode.

I suspect it's because prefabs that was referenced destroyed after exitting play mode? usually how do you solve these types of problems, does it leans more to the code structures?

slender nymph
#

please use a bin site if you are going to share a large stack trace 👇 !code

eternal falconBOT
slender nymph
#

but if you have not written any custom editor code and you don't have any assets that have any custom editor code then it's probably just a random unity error that you can probably clear and ignore

floral wren
amber nimbus
#

should i use deltaTime or is it fine like this?

verbal dome
#

The default forcemode (Force) already multiplies the force by fixedDeltaTime

amber nimbus
#

alright thanks :D

silk night
deft mango
#

about 2 weeks ago i last opened my project and it had no errors and everything was working fine and now i opened it and all of a sudden i got 12 errors and that required me to go into safe mode i went into safe mode and i dont understand whats the problem can someone help me?

silk night
hexed terrace
#

something wrong with the pacakge, have you relaunched Unity ?

silk night
#

Try updating text mesh pro through package manager

#

if that doesnt help restart

hexed terrace
#

(this isn't a code issue, for this channel)

silk night
#

if that doesnt help close unity, remove the library folder, open project (⚠️ takes very long depending on project size)

deft mango
verbal dome
#

So you'd use those for continuous forces and the other two modes for instant forces

silk night
#

oh yeah, makes sense that those modes use it

#

ty for that graphic

wintry quarry
deft mango
hexed terrace
#

yes, just close Unity first

silk night
#

Yes, close your project, delete the Library folder in your project root and open your project

#

that will trigger a full reimport

rocky axle
#

Hi all, I'm working throug hthe beginner tutorial on unity learn and they asked me to make a "MonoBehaviour Script" but I'm not seeing the option anywhere

keen dew
#

C# Script

rocky axle
#

in the tut it showed it listed as MonoBehaviour 😄

silk night
#

The tutorial is most likely done on an older version which has different naming

hexed terrace
#

it's always been C# Script

queen adder
#

what is this channel

frosty hound
queen adder
#

idk

#

There is nothing about code beginner

frosty hound
#

Right. If you're here to act goofy, you will be removed.

steep rose
true lava
#

why my recoil doesnt work :( ?

#

may i share code here?

languid spire
#

yes !code

eternal falconBOT
true lava
#

Wait, the code is very long

silk night
#

then use one of the top links

true lava
#

how?

#

Like this i guess?

ivory bobcat
#

Click the link. Copy and paste your code into the site. Press the save button on the site. Copy the url and paste it here.

true lava
#

Wait, thats the weapon script, i shouldve given the camera script

queen adder
#

Does anyone have a good recommendation for a YouTube series to learn C# in unity?

silk night
eternal falconBOT
#

:teacher: Unity Learn ↗

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

true lava
#

That's the correct script now

true lava
#

I've spent hour and hour just wanting to fix this, still failed :(

languid spire
true lava
#

I deleted again

languid spire
#

why?

true lava
#

It's just annoying for my eyes :,)

languid spire
#

bye

rocky axle
#

is there a way to make it so that when I open microsoft visual studio from Unity, it is automatically setup for c# (shortcuts and autofills, etc)?

frosty hound
eternal falconBOT
rocky axle
#

thank you!!

true lava
#

It's always recommended to leave debug? i though people dont like it? im still beginner

frosty hound
#

You can remove it before you release something. Leaving it in during development is fine?

#

Also who are "people"? Are you working in a large team that these "people" are not liking your debugs?

true lava
#

Im solo

#

So i dont really know other perspective, sorry

#

But thanks though, now i know majority recommend to make debug log stay

hexed terrace
#

it makes no difference to the end user, it all depends on what you want to do

#

I tend to tidy up logs when I no longer need them so they don't get in the way with other development

true lava
#

I see i see, i'll note that tips :)

gleaming plaza
#

why does the highlighting not work half the time, it's getting kinda annoying

cosmic quail
hexed terrace
#

they make a difference to performance, when there's thousands of them being spat out every frame

#

debug.log does not output to anywhere afaik, or that I've ever heard/ seen

polar acorn
#

There's the player log, but it gets wiped every time you start the program and if you're logging so much that filesize becomes a problem for plain text, stop

wheat coral
gleaming plaza
#

like..everything?

rich adder
#

VS is kinda slow

wheat coral
rich adder
wheat coral
# gleaming plaza like..everything?

It's just that this software is a very heavy thing so sometimes it takes longer than usual to load the extension (I mean that highlighting names algorithm)

rich adder
#

its not called Highlight names algorithm, what you're referring to is Intellisense

wheat coral
wheat coral
#

And gives similar methods on the name you writing

#

I mean Similar in name

rich adder
wheat coral
gleaming plaza
#

um also is there a way to make visual studio not open every time I create or delete a script

outer wadi
#

Do you guys know a way for menus not to stack over each other when activated, I can disable and able it but when I enable one and enable another again it just stacks over the previous and the former one don't disable

rich adder
outer wadi
#

ah okay

gleaming plaza
#

and the auto complete stops working

signal tide
#

Hello people can anyone tell me
how do i make unity webgl game landscape by default

wintry quarry
#

it's not something that would be controlled in Unity

signal tide
signal tide
wintry quarry
#

I don't know anything about website design tbh

signal tide
queen adder
#

anyone got youtube series to help me learn C# coding in unity?

wintry quarry
#

well I guess it links to a YouTube playlist anyway lol

deft grail
cosmic rapids
#

hey guys i have some trouble getting the debugger to work,
first of all the attach to unity option does not appear in the left debug section

second of all when I ran "run and debug instead", vs code claims to be attached to unity as it can be seen in the lower part of this image.

however when i play the game in the editor, there is no option to use the steppers or even check the variables

on top of that the left dropdown list of variables is empty

what do I do? I have been following tutorials exactly but can't seem to get the same result...

languid spire
#

json is a data file, you can only debug code

cosmic rapids
#

i set the breakpoint in the singleton which initialises when the game starts

stone ivy
#
public class MyPointer : MonoBehaviour
{
    private void Update()
    {
        var mouse = Mouse.current;
        if (mouse is null) return;

        var move = mouse.position.ReadValue();

        Debug.Log(move.normalized);
        transform.localPosition = move.normalized * 5f;
    }
}

i'm trying to use the new input system to make a basic aiming reticle type thing. Whilst this does track mouse movement, it only moves the reticle sprite in a circle around the player but i don't know why. I tried switching between position and localPosition but that made no difference. The Debug statement prints out a Vector2

#

oh, and i have the CinemachineCamera set to look at MyPointer

languid spire
#

mouse returns a screen position, so you need to convert that to a world position to use in transform.position

eternal needle
cosmic rapids
snow warren
#

hey
i am encountering a trouble with position of UI when i instantiate a prefab object

wintry quarry
snow warren
#

i want to right click on a UI button
i added listener for right click
on that right click i want to instantiate a prefab like a menu over that UI button

#

but the problem is the position of the instantiated object
lets suppose i get the cursor position when right click and instantiated the prefab there

#

now if the UI button is on the bottom of the game then the instantiated prefab will be outside the canvas

#

i dont know the solution to such problem as its my first time encountering one

#

any helps are appreciated?

#

thanks in advance

wintry quarry
#

how and where are you spawning it?

snow warren
cosmic quail
cosmic quail
#

recttransform.anchoredposition

snow warren
#

as rects are universal

#

but i have never worked with rects before

#

any guide that can tell me how they work

#

ok

#

sorry not rect transform but rect

#

rects are universal

cosmic quail
# snow warren sorry not rect transform but rect

but basically you can just add a bit to the y value of the buttons recttransform's anchoredposition and set the prefab's recttransform's anchoredposition to that. and then maybe you also have to change the rects' pivot point

snow warren
#

consider a button that is on the top of the UI

#

then doing so will again put it out of the canvas

#

need a better solution

cosmic quail
snow warren
wintry quarry
# snow warren thanks in advance

the fact is that positioning this thing properly depends on several factors, the largest of which being:

  • What Canvas render mode are you using?
wintry quarry
#

IIRC you can basically do ScreenToWorldPoint on your mouse position and use that result directly for a Screen Space - Camera canvas

snow warren
#

let me see

snow warren
snow warren
#

hey
is there a way to post process screen spaced canvas

rocky canyon
#

and then assign the camera that has the post processing effects on it

snow warren
#

i want to keep the screen spaced

#

due to some heavy rect stuff i am doing

rocky canyon
#

it is screen-spaced..

#

screen-spaced.. camera

#

not world space 🤔

snow warren
#

screen space overlay

#

it sets the UI in the world position

rocky canyon
#

if u want to keep it overlay there might be some work-arounds to get post processing

snow warren
#

but found no hope

#

so asking here now

rocky canyon
#

this is what i found, and was going off of

snow warren
#

let me see

rocky canyon
#

i dont think it will mess w/ ur overlay stuff..

#

it just adds and focuses a camera on it

snow warren
#

i wont know unless i read or try

snow warren
hearty apex
#

Combine it with pointer events which contain important information about clicks.

delicate slate
#

i am new with code and i would like to set a public GameObject Cube; to already be there when i put it on an object like i can with a "public string text = "text""

slender nymph
#

you have a couple of options, you can either assign it in Reset() using a method that searches for the desired object (like GameObject.Find if the object is supposed to be in the scene), or you can assign a default reference in the script's import settings, but that only works with prefabs. both of these options are also only really going to work for when you add the component via the AddComponent menu in the editor

wintry quarry
#

so you need to get the reference some other way. Either assigning it in the inspector, or with some other code in a function later.

delicate slate
#

ok thank you

lone sable
#

Im trying to save my UnityEngine.Random.State however, it doesn't seem possible. to load it back in as the values just get 0'd out.

Is there any possible way to do this?

slender nymph
#

how are you saving it

lone sable
#

public Serializable class with a UnityEngine.Random.State property that I assign before saving to a json file.

slender nymph
#

and have you confirmed that it has been saved correctly? and that you are also correctly deserializing it?

lone sable
#
[System.Serializable]
public class GameStateData {
 public UnityEngine.Random.State seedState;
}

public void Save(){
 data.seedState = Utils.GetRandomState(); //Returns the current state.
//Saves to Json using JsonConvert.SerializeObject
}

public void Load() {
 //Load from Json using JsonConvert.DeserializeObject<T>(LoadJson(inFileName));
//Checking the seed state here shows all 0's.
}
slender nymph
#

ah yes, truncated code that doesn't actually show you doing anything or even how you've confirmed any of this actually works as you intended

lone sable
#

Theres not much else to show at the end of the day. I store the seed state into a class, Serialize the object using Newtonsofts Json, look at the json file, and it shows it as being empty.

slender nymph
#

although if i were a betting man, i'd say that whatever "Utils.GetRandomState" is, is probably where your issue lies

lone sable
#

And in editor, it shows the proper values.

slender nymph
#

well until you stop cropping out important context, i'm not going to bother helping so good luck figuring this out

lone sable
#

Will do.

blissful yew
#

I'm fading out a sprite. The debug.log is showing a smooth progression from 100 to 0 alpha, but the actual sprite during gameplay doesn't fade at all until it hits 0 alpha, at which point it vanishes, and the sprite render doesn't display the alpha changing until then. What the heck..? If I manually drag the alpha slider it works fine.

slender nymph
#

Color uses values from 0 to 1. Color32 can use values from 0 to 255, neither use 100 for 100% alpha

blissful yew
#

Fixed, thanks.

#

The inspector shows 100 being the max alpha smh

slender nymph
#

sounds like you've got your color picker set to HSV

blissful yew
#

HSV feels like the most intuitive by far

#

except in this case apparently

slender nymph
#

okay well those values you see don't directly correspond with the values you would use for the Color or Color32 data types. set it to 0 - 1.0 for the values you'd use for Color and 0 - 255 for Color32

prime cobalt
#

hey there's like a split second delay between all of these audio clips playing and it's distracting because there's music baked into them. Does anyone know how to get rid of the delay?

deft grail
prime cobalt
#

Ok yeah there's a tiny skip but it's far less noticable, thanks!

queen adder
#

Anyone got a video i can watch to learn C# coding USING unity

steep rose
#

you can !learn this course of unity or use any C# video on youtube to learn C# solely

eternal falconBOT
#

:teacher: Unity Learn ↗

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

steep rose
#

I would recommend by learning from documentation and using unity tutorials as a reference, since if you solely use tutorials from youtube you will learn nothing

#

there is this tutorial from Imphenzia which I heard was good for beginners
https://www.youtube.com/watch?v=pwZpJzpE2lQ&ab_channel=Imphenzia

EXPAND for Time Stamp Links -- This is the most basic Unity tutorial I will ever make. If you are brand new to Unity, or if you want to make sure you’ve covered the basics, and if you want to learn how to write your first C# script - this is the video for you!

Over the course of 2 hours, I go through the User Interface, Game Objects, Transforms...

▶ Play video
wide finch
#

so I'm trying to use daves tutorial for fps camera movement and whenever I try to use his code that he shows the console says that Imput, sensY, mouseX, and mouseY dont exist for current context, and Time does not contain a definition for DeltaTime. I tried looking this up but could not find anything to help me. can anyone here tell me why this happens?

#

also I am not just relying on tutorials, I was just using this one so I can start somewhere

wide finch
# wide finch so I'm trying to use daves tutorial for fps camera movement and whenever I try t...

FIRST PERSON MOVEMENT in 10 MINUTES - Unity Tutorial

In this video I'm going to show you how to code full first person rigidbody movement. You can use this character controller as final movement for your game or build things like dashing, wallrunning or sliding on top of it.

If this tutorial has helped you in any way, I would really appreciate...

▶ Play video
deft grail
#

for sure you did

wide finch
#

hmmmmmm, ok

deft grail
wide finch
#

but what about the other stuff like sensY and mouseX and Y

#

just copied wrong?

deft grail
wide finch
#

imma look at the pdf in his description, it may explain it

cinder schooner
sudden pilot
#

guys what is the best way for getting trigger in some animation ( like an attackt animation combo)

willow iron
#

greetings. want to make it so that when i interact with an object the camera zooms in to the object so that the player can interact with it further. is cinemachine state driven camera the best way to do this. I just wanted to check and make sure that there isn't a more efficient way before i commit to this.

sudden pilot
#

if ı attackt with hammer animation for example it should be more slow hammer collider or a katana is too fast

#

how can ı use this coliders exactly. This colliders should be there for just attackt actions

#

ı dont even know how can ı search this thing on internet and ı asked here

#

my english not that good btw.

rich adder
cinder schooner
sudden pilot
cinder schooner
#

yes, for this you can use animation events.

sudden pilot
#

ı want to change location of it to where ı want same like elden ring or black myth wukong games

rich adder
#

so just move it during the animation

#

you need to record the keyframes

cinder schooner
#

you want to move the colliders?

sudden pilot
#

but when it effects with collider it will be Player tag pr something

#

ı want a spesific collider for thıs anımatıon

sudden pilot
rich adder
sudden pilot
#

ı need to learn the even just title of this

#

so ı can search on ınternet but ı cant fınd

sudden pilot
cinder schooner
# sudden pilot yes

So what you want = when an attack animation plays you want the colliders to be active and look for contacts and disabled for certain animations, you also want to move the collider(I guess with your hand or if you have a sword), Is that correct?

sudden pilot
#

ı want a spesific one

sudden pilot
#

but if ı do it with in player colliders or something it wıll be by Player tag

cinder schooner
#

no problem, that isn't hard.

sudden pilot
#

ı dont want the tag wıll be Player or somethıng

cinder schooner
#

1.Open the animation window and select your attack animation

#

2.Attach a script that will listen to animation events on the gameobject containing the animator component.

sudden pilot
#

if you telling about using animator ı already know it

cinder schooner
#

No i am not, i will get your job done!.

#

Do you know how to add animation events?

sudden pilot
#

with clıckıng top of frame part

sudden pilot
#

even if ı can do it with some other gameobject's collider ı need to know how can ı contact them

cinder schooner
#

oh thats simple,

true lava
#

Any help here?

#

//stop building part make the drag and drop system wont works

#

when i delete that part it works again, but i should not delete it because i need it for my building system, Ghost thingy

cinder schooner
#

you need a script on the object with your collider which will have this code : private void OnTriggerEnter(Collider other)
{
if (!other.CompareTag("Player"))
{
// play effects
}
}

This function tells if the trigger got hit, it gives you a ref to the other collider, Also make sure to set the collider of the (sword) to istrigger., now in this function you can check if the trigger is not equal to the player tag.

sudden pilot
#

actually look

#

like a raycast

#

it is not connecting our colliders

#

but it effects and ı can get ınformatıons

#

but it is just going one way

#

ı cant scale it or move good

#

it is controlling from inside code

#

and unknown

cinder schooner
#

so you want to raycast from the (sword) starting point till the ending point?

#

and use that instead of hit boxes?

sudden pilot
#

no just asking is there any better option than raycast for it

#

easy to controll and getting informations

#

and ı can connect with animations

#

best way is animations right?

#

ı mean animation window

cinder schooner
#

there are two ways, the first one is having a script listen for trigger collisions and using a raycast, raycast would be slitely innacurate as the sword is 3D while a ray is a flat line,.

rich adder
#

if you want to get information the best way is the raycast, the triggers are the easiest

#

you dont have to use the shape of a line, use Overlap or other casts

cinder schooner
#

yes, but that wouldn't be performant, i think triggers is the best option.

rich adder
#

rays are cheap

cinder schooner
#

"other casts"...

rich adder
#

most physics queries are, esp if nonalloc mode is used

cinder schooner
#

handling these is also a bit harder.

sudden pilot
#

when enemt get effects by player's collider, enemy will take information of ' Player ' tag

#

ı dont want this

#

that ıs all ı want

#

ı want something like collider

rich adder
#

what effects ? particle effects

sudden pilot
#

but ı wıll put many anımatıons of attackt and they should be dıfferent each of them

rich adder
#

you're like confusing the question tbh

sudden pilot
rich adder
cinder schooner
#

at the contact point

sudden pilot
#

this attackt trigger exactly follows the attackt and it influence player anywhere and anytime it wants

#

what ıs the way of doıng ıt

cinder schooner
#

this means the enemy needs to talk with the player, So you can use an interface

#

like this : public interface IHittable{}

#

and inside the body of the interface you define the functions to do stuff in the player,

sudden pilot
#

maybe ı should create an empty game object and creatıng all triggers here and contacting wıth maın player

cinder schooner
#

so like :
public interface IHittable
{
void Hit();
}

Then your player script would :
public class Player : Monobehaviour, IHittable
{
public void Hit()
{
// in here is where you would do your falling animation or rolling animation
}
}

#

your enemy could then do a try get component of type IHittable and then call the hit func if it is not null

sudden pilot
#

before thıs ı need to learn ınterface from youtube or smth

#

@cinder schooner thank you buddy <3

vocal sand
#

hey i need some help with the tree placing tool on terrain

#

it says that my prefab has no valid mesh renderer

#

but i checked and , i think it has

worthy veldt
#

so i tried to convert multidimensional array (well. technically array of list) to json using JsonUtility.ToJson but it doesnt work.

#

is it possible with array of array, list of list or list of array ?

worthy veldt
#

tbh im very suprised it is not possible to do it directly, i only need 2 list currently but its very likely that ill need more in the future. my online seach leads me to using newtonsoft extension but i want to build from scratch.

flat fossil
#

Hi, does anyone know how to do random item spawning in Unity?I have an item of one type that the player has to collect but I would like it so that each game spawns 8 items in a different place, for example I set 20 spawnpoints.

modest dust
#

Copy the spawn points into a list, choose one at random via Random.Range, put it into the result list/queue/stack, remove it from the starting list

#

Repeat 8 times, use result list/queue/stack to spawn items

#

Another way is to just shuffle and iterate through the spawn points pool and either choose one or not based on chance = needed_left / in_pool_left

#

in_pool_left decreases with each iteration, needed_left decreases only when a spawn point is selected, so at one point if nothing is selected you're at least guaranteed a 100% chance to finally select something from the end of the pool

flat fossil
#

thanks

cinder mason
#

Im making a dungeon generator and what im doing is picking a room prefab, then getting its collider2ds size, seeing if it fits, then spawning it in, however, the size is always 0,0 for some reason?

burnt vapor
#

!code

eternal falconBOT
cinder mason
ivory bobcat
#

bounds is a struct so you could probably just assign the room bounds the bounds unless you're not wanting the other details.

cinder mason
#

the size is still 0,0

ivory bobcat
#

Other than that, log the room prefab and it's bounds to see if it's correct

#

For example: cs var bounds = roomToSpawn.GetComponent<Room>().roomFill.GetComponent<Collider2D>().bounds; Debug.Log($"The room name: {roomToSpawn.name}", roomToSpawn); Debug.Log($"The room bounds: {bounds}", roomToSpawn); Debug.Log($"The room size: {bounds.size}", roomToSpawn);Edited

#

Where clicking any of those messages in the console window would highlight the room in the scene.

#

Show us the logs

cinder mason
#

i know the bounds are correct because when i tested instantiating it in the bounds are correct. (though im not going to spawn the room in every attempt to make it run faster)

#

ill try the debug stuff though

cinder mason
# ivory bobcat Show us the logs
The room name: SHOP-ROOM
The room bounds: Center: (0.00, 0.00, 0.00), Extents: (0.00, 0.00, 0.00)
The room size: (0.00, 0.00, 0.00)
night mural
#

bounds are in world space, maybe they don't really exist if the object isn't instantiated in the world yet?

#

yeah, I think you want collider.size, not collider.bounds.size

scarlet river
#

Hey Unity hive-mind! I've been racking my brains over this one. I'm trying to render a grid on a plane and this is my GridManager.cs script. I get weird artifacts when I hit PLAY. I have another script GridVisualizer that handles the actual lines. Do you know what the reason for this could be? Thanks!
https://hatebin.com/vohdfcidaj

proven matrix
#

Why cant i apply my idle sprites to my animation controller

short hazel
smoky raft
#

Hi everyone, I want to change the weapon name in a Unity 2D game on Steam. Which file should I look for to edit the item name?

cunning ether
#

Hello, so i am trying to use the new input system and i couldn't find a way to let the character constantly jump. I need to press the jump button all the time. What is the fix for it? Can somebody help?

short hazel
smoky raft
#

ok thank you

short hazel
cunning ether
#

Ahh

#

used that for looking around didn't think to do the same for jumping

#

thx

scarlet river
short hazel
#

There might be a Grid component that you can attach to the object

#

See if that exists

#

It does, but it's more of a placement helper

#

So I think you'll have to roll your own, or find an asset on the store that does it for you

proven matrix
#

Why does my running animation look like this?

worthy veldt
fading vigil
#

I have a bit of a problem rn

#

transform.position += transform.forward * 10;

#

this code doesn't work for some reason

#

it says "Object reference not set to an instance object"

#

everything else works fine

keen dew
#

Show the full script and the full error message

fading vigil
#

Alr

#

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

public class PlayerRayCast : MonoBehaviour
{
public float cooldownE = 10f;
public int energyQ = 60;
public float cooldown = 0f;
public GameObject Player;
Ray ray;
RaycastHit raycastHit;
Vector3 RayPosition;

void Update()
{
    cooldown -= Time.deltaTime;
    ray = new Ray(transform.position, transform.forward);


    if (Physics.Raycast(ray, out raycastHit))
    {
        if (raycastHit.transform.tag=="wall")
        {
            RayPosition = raycastHit.point;
        }
    }

    if ((Input.GetKey(KeyCode.E)) && cooldown <= 0.0f )
    {
    if (raycastHit.transform.tag != "wall") 
        {
            transform.position += transform.forward * 10;
            cooldown = cooldownE;
        }
    else if (raycastHit.transform.tag == "wall") 
        {
            transform.position = RayPosition;
            cooldown = cooldownE;
        }
    }
}

}

keen dew
#

Full error, including the line number

#

but I assume it points to the if (raycastHit.transform.tag != "wall") line instead because that would be null if the raycast doesn't hit anything

fading vigil
keen dew
#

right, line 31 is if (raycastHit.transform.tag != "wall")

faint agate
#

Hello, so ive been trying to use dot product to accomplish a goal which is making the screen to turn red with full screen pass renderer as the player does a 180. The screen effect(it turning red) percent will be connected as the player turns around so it wont be at 100% unless the player has done a full 180, this is why im using dot product. There is no certain trigger and this will happen when i press play. I would like the ditherspead float to change according to the player turning and dither spread(float) starting at 0 and hiting x when the player does a full 180.
But Im so confused using dot product and looked everywhere to help with what im trying to do.
https://pastecode.io/s/kwbp6dmu
here is the code I have so far. What you see is how far I got with dot product and me testing everything with the press E to make sure the screen renderer works

willow iron
#

hey guys, uhh watching a tutorial for the state driven cameras on cinemachine, just found out you need to parent the virtual camera to the cinemachine brain... kinda already parented the virtual camera to my first person character/controller and did a shit ton of code surrounding it. anyway to do this without redoing the entire project?

keen dew
#

Then you can divide that by 180 and plug it into the lerps

faint agate
gleaming kraken
#

discovering Invoke() after using coroutines for the smallest of things is actually crazy, such a time saver.

ivory bobcat
# gleaming kraken discovering ``Invoke()`` after using coroutines for the smallest of things is ac...

They do differ though
https://www.codinblack.com/how-to-run-a-method-at-certain-time-intervals-in-unity/

The last difference between Invoke and Coroutine which we will cover is the execution condition after the deactivation of the object. Invoke and InvokeRepeating do not stop after the game object is deactivated. On the other hand, this not true for coroutines. They stop after the game object is deactivated or destroyed. Therefore, you should use Invoke or InvokeRepeating, if you would like your method to continue running, even though the object is deactivated after the method is triggered.

faint agate
keen dew
#

You can just use the camera's current rotation

#

and you already store the initial rotation

frigid crescent
#

hi, ive just joined to try and find some help for a little camera rotation im trying to do, going onto unity in 3D after using GameMaker is a bit of a headfuq lol

#

where should I ask?

gleaming kraken
deft grail
earnest wind
#

is this something normal?

frigid crescent
#

You can see the camera angles on the right in the video going like mad lol

deft grail
frigid crescent
#

I did try with 1, gave the same effect, i increased it to 3 so I could ssee what was actually going on

faint agate
keen dew
ivory bobcat
fading vigil
keen dew
#

You have to put it inside the first check that makes sure the raycast has hit something

gleaming kraken
#

and i just know learned of its existence

#

so goated

fading vigil
keen dew
#

The first if statement in the code

fading vigil
#

Alr

vale geyser
#

I am not sure if it could be due to a mistake in one of my other scripts

faint agate
keen dew
#

Take the lerps from the coroutine and replace elapsedTime / _hurtDitherFadeInTime with angle / 180

languid spire
languid spire
#

so cardScript is null

vale geyser
languid spire
# vale geyser

also that says line 52 which does not match with your script

vale geyser
languid spire
#

ok, so if you expect help the least you can do is provide accurate and complete information

vale geyser
#

that's my bad, sry

rich adder
#

move like some sort of camera? wdym by that?
also the slerp is hella wrong

#

that doesnt explain what you mean by that..

#

anwyay fix the wrong Slerp first and go from there

#

right now the Slerp is saying Turn the transform.rotation in this look direction but only give me 15% of it out of 100%

#

you should not be using a constant

faint agate
keen dew
#

The easiest way would be to use an object that rotates only on the Y axis with the camera. For example if you have a separate player model then take its rotation

toxic void
#

Hey, why am I not able to call the method I defined above? Am I missing something? It doesn't autocomplete to it and gives me an error for trying to call it

keen dew
#

You've named the variable the same as the method

toxic void
#

Is that not allowed?

keen dew
#

It can't know which one you mean. It's trying to call the variable

toxic void
#

Oh I just need to remove the capital letter

#

my bad

faint agate
toxic void
#

Hey, why does the playerMovement variable get set to null? I checked and the player variable doesn't get set to null, only the playerMovement is, and I'm absolutely sure the instance rocket has this script.

languid spire
#

player does NOT contain a PlayerMovement component

toxic void
#

But it does...

languid spire
#

and is that the only gameobject called Rocket?

toxic void
#

yes

languid spire
#

ok, Debug.Log the InstanceId of player

toxic void
#

This is the scene hierarchy

toxic void
languid spire
#

ok, now switch the Inspector to Debug mode

toxic void
#

yep that's not the ID

languid spire
#

told you

toxic void
#

How is that possible?

languid spire
#

there is something else there, maybe in the Asteroid prefab

#

or RocketModel prefab

toxic void
#

ohh

#

yeah

#

The model consists of a part called rocket

languid spire
#

there you go then

toxic void
#

I'll just change it's name to player

languid spire
#

why not make a reference and store it in GameManager, presuming that is a Singleton?

#

then you can lose the Find completely

toxic void
#

Because the script I'm using is on a prefab

languid spire
#

does not matter

toxic void
#

Really?

languid spire
#

really

toxic void
#

What if the prefab is in a different scene

#

would that just land an error>

#

oh wait nvm

languid spire
#

as long as Rocket and GameManger are DDOL, no problem

toxic void
toxic void
frigid crescent
#

Not sure where else I can post this without interrupting , sorry .

I'm trying to get my camera do a simple lerp to a new rotation on ONE axis ( like the video attached ) .
I've tried with some code to get the camera angle to just change up and down before adding lerp, and it offset my camera Y rotation for some reason when turning my player object? ( I've attached the code I tried using )

frigid crescent
#

Camera.main.transform.eulerAngles = cameraRotation; seemed to be the line causing the weird Y offset, i dont know why it did that though , the X axis changing on button pressed X and C worked fine though

languid spire
#

you were seeing this in the inspector?

frigid crescent
#

no, in game, ill record a video if you like

#

:)

languid spire
#

nothing there will change the y rotation

frigid crescent
#

Exactly, which is why im confused !

#

heres a demo of the outcome when the script is on, its changing the camera Y rotation . When off it shows the expected outcome

#

My player movement controller references euler angles aswell for the movement is this why maybe?

languid spire
#

So what did I ask you, to which you replied no?

frigid crescent
#

Ah sorry, I misunderstood you

languid spire
#

the answer is simple, ignore the inspector
when you do
eulerAngles->Quaternion->eulerAngles (which is what you are doing)
the resulting eulerAngles will almost never be the same as the originals but the actual rotation will be

frigid crescent
#

I'm sorry I still think im struggling to understand

#

ignore the inspector?

languid spire
#

yes
A Quaternion is a black magic box that represents a rotation, correct?

frigid crescent
#

if you say so?

languid spire
#

dont you know what a Quaternion is?

frigid crescent
#

sorry mate i'm new to the 3rd dimension

#

nope ,

languid spire
#

ok. transform.rotation is a Quaternion
transform.eulerAngles is a Vector3 which can be set with degrees which you and I understand.
Internally these degrees are transformed through black magic into a Quaternion and stored in transform.rotation
now..,
when that Quaternion is turned back into eulerAngles to be shown in the inspector the values are different because one Quaternion can be represented by many euler angle combinations and the system just choses one of those which is almost certain not to be the one you put in in the first place

frigid crescent
#

ahhh that makes more sense

#

yeah that helps

#

so what would be the correct way to go about it to stop that mis-representation

languid spire
#

hence 'ignore the inspector' just take it for granted that the rotation represented is the correct one

languid spire
frigid crescent
#

i think you might have misunderstood me , unless there is genuinely no solution for my game-breaking issue?

languid spire
#

there is nothing game breaking there, you are looking at the inspector data and thinking it is wrong when it is not

frigid crescent
#

no mate im looking inside of MY game. The video shows me playing with the script on, then without

#

the first button I pressed in the video is left, which should turn the camera left to look down the corridor as shown in the inspector and later shown by the working demo in the video

languid spire
#

then why are you constantly refering to the inspector in your vid?

frigid crescent
#

To show that its changing my cameras Y value when my player turns , when im only trying to get the camera to look up and down on the X axis when pressing X / C

languid spire
#

you have totally ignored everything I just explained to you

frigid crescent
#

Because im just confused now

#

lol

#

after you saying theres not a correct way to go about it

languid spire
#

what don't you understand about 'ignore the inspector, the values you are seeing are not what you expect but the rotation they represent is what you asked for'?

frigid crescent
#

right im sorry mate, but it just seems your way of explaining things doesn't work with me personally , i'll find help elsewhere because your just being unnecessary

languid spire
#

good luck with that

ruby python
#

Having a brain fart.

Building up a simple spaceship controller (steering dealt with by the mouse and movement driven by physics.

I'm getting a lot of 'jitter' when moving.

Video for reference.
https://streamable.com/o07oaq

Full controller code
https://hastebin.com/share/awekuvocak.csharp

I'm 99.9% that the following is the culprit and I know why, but my brain isn't cooperating and I can't think how to 'blend' the vertical and horizontal movement (if that makes any sense)

    void MovePlayer()
    {
        playerRigidBody.AddForce(transform.forward * playerFlightSpeed * moveZ, ForceMode.Impulse);
        playerRigidBody.AddForce(transform.right * playerFlightSpeed * moveX, ForceMode.Impulse);
    }

Watch "2024-10-12 19-17-04" on Streamable.

▶ Play video
normal blade
#

I'm using Addressable to create a Scene conversion and I get an error called Error unloading scene MainMenu: Attempting to use an invalid operation handle. But the scene conversion works well. How do I fix the error?```csharp
private async Task UnloadSceneAddressable(string sceneName)
{
if (_loadedScenes.TryGetValue(sceneName, out AsyncOperationHandle<SceneInstance> handle))
{
if (handle.IsValid())
{
try
{
AsyncOperationHandle<SceneInstance> unloadHandle = Addressables.UnloadSceneAsync(handle);
await unloadHandle.Task;

                    if (unloadHandle.Status == AsyncOperationStatus.Succeeded)
                    {
                        _loadedScenes.Remove(sceneName);
                        Debug.Log($"Scene Unloaded: {sceneName}");
                    }
                    else
                    {
                        Debug.LogError($"Failed to unload Scene: {sceneName}");
                    }
                }
                catch (Exception e)
                {
                    Debug.LogError($"Error unloading scene {sceneName}: {e.Message}");
                }
            }
            else
            {
                Debug.LogWarning($"Handle for scene {sceneName} is not valid. Removing from loadedScenes.");
                _loadedScenes.Remove(sceneName);
            }
        }
        else
        {
            Debug.LogWarning($"Scene was not loaded: {sceneName}");
        }
    }```
paper peak
#

Why isn't visual code studio giving me C# stuff

#

It says C# up here

cosmic quail
eternal falconBOT
paper peak
#

Fixed, thanks!

steep rose
#

also this wont lerp but should fix the other problems you mentioned although I didn't test it though, so hopefully it does work.

sand snow
#

why wont this work, it keeps saying cannot convert vector3 to float but doesnt it need numbers in order to change the rotation?

 if (Input.GetKey(KeyCode.A))
 {
     rb.rotation = new Vector3(rotSpeed, 0, 0);
 }
slender nymph
#

2d rigidbody uses a float for its rotation since it is only around the z axis

#

unless rotSpeed is a Vector3, in which case why are you using it as just the X axis of a Vector3?

sand snow
#

oh yeah i meant to put it on the z axis ty

#

but i still dont understand the problem

slender nymph
#

which is the issue, the fact that you are using a 2d rigidbody? or that rotSpeed is a Vector3?

sand snow
#

im using 2d

slender nymph
sand snow
#

but then how do i change the rotation?

#

(while clicking a key)

slender nymph
#

use a float, not a Vector3 because the rigidbody's rotation is a float

sand snow
#

ohhhh

slender nymph
#

also note that assigning rb.rotation assigns a specific rotation, not a speed at which it will rotate

sand snow
#

yes ik i just didnt know what to name the variable

#

im having another issue and i think i know the problem I just dont know how to fix it

#

im trying to make a remake of the astroid game if you know it, youre basically a small spaceship and you have to shoot astroids before the hit you or you lose

#

I want my player to move in the direction its facing but it only moves in one direction regardless or the rotation

#

here is my code

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



public class PlayerMovement : MonoBehaviour
{

    public float speed;
    public float rotSpeed;

    public Rigidbody2D rb;

 
    void Start()
    {
        rb = GetComponent<Rigidbody2D>();


    }

  
    void Update()
    {
        if (Input.GetKey(KeyCode.W))
        {
            rb.velocity = new Vector2(speed, 0);
        }
        else
        {
            rb.velocity = new Vector2(0, 0);
        }
        
        if (Input.GetKey(KeyCode.A))
        {
            rb.rotation = rb.rotation + rotSpeed;
        }

        if (Input.GetKey(KeyCode.D))
        {
            rb.rotation = rb.rotation + -rotSpeed;
        }
        
    }
}
spare pumice
#

does anyone know why unity wont download?

slender nymph
sand snow
#

okay thank you i will try it

slender nymph
eternal falconBOT
#
When Unity fails to install checklist
  • Make sure you have enough space including on C: drive.
  • Check that it's not being blocked by antivirus/security programs.
  • Look through the logs for a real reason why the setup fails they are pinned [here](#💻┃unity-talk message).

If you still have issues, perform a clean install in another location:

  • Install the Hub and Unity in a non-system drive or a clean new folder in the root of C: drive.
  • Failing that use the recovery Refresh option or reinstall OS entirely then repeat the previous step.
sand snow
#

only problem im having now is that when i rotate it slows down my movement alot

#

im almost stationary while rotating

#

i fixed it

#

it was because it was in Update not FixedUpdate

ivory bobcat
# gleaming kraken and i just know learned of its existence

The info that I provided still applies though. For instance, if you had something that would delay a few seconds before executing but disabled that object, invoke would still fire and do it's thing regardless of the state of the object. Which could potentially do something you aren't expecting.

eternal needle
teal hazel
#

Hi, I know that for the x and y axes, we can use the Tilemap Collider with a Composite Collider, but I need to use a Tilemap on the x and z axes. I had to create my own script for generating colliders from my Tilemap. It was quite complicated, especially regarding optimization, and I wanted to know if there is a better way to do it.

Thanks.

#

The generation time is very good, but I'm bothered by having so many colliders in a single GameObject. It feels like something isn't right.

rigid stratus
#

I know this is a very general question but does anybody know how people get to be able to be such good coders who just know what to do because Ive been trying for a while but can't progress much.

paper peak
#

You learn out of necessity

#

"I need to make a script that makes this bomb explode"

#

Search on how to do that, make it work and then you'll have knowledge for future coding that doesn't necessarily have to do with anything you did before

rich adder
#

pretty much, break down the bigger problem into smaller easier to solve parts that all come together for your feature

teal hazel
#

Keep in mind that you can make very good games by being an average developer, it depends on the "difficulty" of your project

rigid stratus
teal hazel
#

if you want smtg more complex you can do a tic tac toe game in the console for exemple

queen adder
#

my first C# project was a linux terminal but in windows, with some commands and stuff, i used the same project idea when i started to learn C++
if you wanna learn how to code you gotta know your understanding level, some people understand stuff faster and some people take more time, dont learn from youtube because you will be tempted to only copy and paste stuff, go to forums and read documents and stuff, and after that go watch youtube tutorials and try to get ahead of the guy ur watching

eternal needle
#

Making stuff in console wont get you nearly as far as doing the actual hard problems from websites. And at least websites have ratings like how hard a problem is, plus testing to see if your solution works

rigid stratus
#

Thanks guys for the help I will try these

queen adder
# rigid stratus Thanks guys for the help I will try these

learn base C# (the syntax and stuff like that) and then slowly move on towards the unity api, learning pure C# will take a while and without a specific use it will he hard to learn, hop in unity, read some stuff and the try to do it yourself, good luck

zealous junco
#

void FixedUpdate()
{
float horizontal = Input.GetAxis("Horizontal");
float vertical = Input.GetAxis("Vertical");

    rb.AddForce(car.forward * vertical * Acceleration, ForceMode.Acceleration);
}

I made this for a car controller, but it just doesn't move. I've assigned values to everything but it just doesn't move.

languid spire
rich adder
#

GetAxis should be fine

rotund hull
#

How do you declare and fill a dictionary in the same line?