#💻┃code-beginner
1 messages · Page 732 of 1
whell they could disable the character controller component before they upload it to the asset store...
b/c it helps to know the basics before jumping into the water...
even teh most basic scripts involve lot of game-dev magic..
1 misspelling can break a whole game
plus it helps to know the structure...
what parts make up that object..
(this is one of the problems occuring right now)
i mean how copying a yt tutorial cant work
what is this lmao
public override void
are you actually inheriting from a class that has a virtual/abstract method called OnStateExit?
And the OnStateExit has to come from an inherited class, of which contains that method to be overridden etc
this is unnecessary
it's convention to put the modifiers in that order but not necessary
Fair game, I just know I've had errors based on wrong order of the modifiers, switched two around and it worked
sounds more like you put the return type before an access modifier
knowing me...sounds likely lol, I have too much going on, so probably missed that
Hello,
I am making a 3D beat 'em up with light attacks and heavy attacks.
what is the best way to handle damage done by the Player?
two variables similar function Damage(variable1);
altho doesn a single swing destroy every little piece anywhay?
health -= variable;
if health < maxHealth -> destroy()
I've looked all over for help but have had no luck
How can i shoot a "ring" of projectiles around and outwards from my enemy.
It needs to be variable dependant on how many projectiles i want but still evenly spread out in a circle
//for (int i = 0; i < amountOfProjectiles; i++)
?? somehow get a direction for each bullet
Instantiate bullet at enemies position, with new custom rotation.
I imagine it has something to do with dividing 360/ amountOfProjectiles
Then converting that into radians or something but im not sure how to do that...
Mathf.deg2Rad() double check spelling, but it converts degrees to radians for you
there is no need for radians here, not even sure why you'd think there is. but 360 / number of projectiles would get you the angle you need between them (might need to subtract one from the count for the proper angle), then you can get the direction using a for loop, that angle you previously calculated, and Quaternion.AngleAxis
Like i said I'm not sure how to do it. How would i use Quaternion.AngleAxis in this case?
Quaternion.AngleAxis(angle,position)?
I need some math help for a Unity script (that I want to create). Not sure how to math this. I have two floats that can be between scaleSizeMin=0.4f and scaleSizeMax=3.0f. I use a Random.Range to pick a # between those. I want to set Rigidbody mass depending on that # chosen so we increase mass between say +1 - 4. How would I do that? (I know how to set mass itself).
you wouldn't use a position as the second parameter, did you look at the docs for it?
I was following till the end, whats so complex about adding a number to mass?
smh.
perhaps it needs explaining a different way
Yes just now
Its not working how i would expect
show what you actually tried
The mass would be increased depending on the randomized number and the range itself. Look at it like 0.4f - 3.0f and 3.0f is 100% of the range. The mass would be increased depending on a percentage of that range. So if our scale increase 25% we increase mass by 25%.
inverse lerp between those values, then use the returned value as the multiplier to increase your mass by
but also why not just use a number from 0 to 1 at that point if you aren't even using those values directly?
Yea i was confused by this, what is the point of doing a random value between this other range to then not need it in that range 😐
Well I'm using those values directly to increase the sprite size
Right, well a random value from 0-1 is easier to work with, can be used to inc mass easier
then with a normal lerp you can do the other range
you're also using a value called "angleIncrement" but then not incrementing it
Im not sure what else is supposed to go there
if only the docs said
Meaning if I use 0-1, I kind of automatically know the percentage?
Got ya
Yea it makes more sense to do it that way round instead of requiring an inverse lerp
Yea I see what you mean now
0-1 number range ❤️
Also could maybe move the decimal over and use it for size hmmm
The doc uses Vector3.up but it just says to use a position
it absolutely does not say to use a position
Regardless using Vector3.Up wasnt working anyways
well you need to use the axis you want the rotation to be around, not just some random guess
thinks out loud so if my random is 0.35 I can move the decimal over, get 3.5 and increase the size by 3.5. If I get .85 and that's too high I can just set a limit. Nice. Cool.
that works
right on I like it lol
Okay im just not sure what it means by that.
I want to rotate on the Z axis? so Vector3.Forward?
a value from 0-1 can be used with Mathf.Lerp() to select a value in a custom range
and then can also be used directly with mass via mass += mass * rand to increase it by 0%-100%
yes, if you want to rotate around the Z axis you would use Vector3.forward as the axis of rotation for that method
Okay thank you that method is really what i needed, thank you so much
Got it working
Hi All, I'm trying to learn Unity and am making a really simple VR scene where when you touch a block it explodes. I can make the block explode if it's touched with anything else other than the player's hand which is the one thing I want to trigger the explosion. I've tried adding a rigid body and collider sphere to the OVRRightHandVisual & OVRRightControllerVisual and added a cube that I verified triggers the explosion of the block to the hand/controller visuals. Neither method will trigger the blocks. I've tried updating the code on the block for OnTriggerEnter and OnCollisionEnter and neither works if it's the player, but works ok if its the floor plane or another block, etc. Is there something special you have to do to make the player interaction work?
are you checking against player game object using the tag system?
allocate the player game Object the tag "Player" its built-in, then in your code check against it example OnTriggerEnter(Collider other) { if (other.tag == "Player") etc... }
don't use string equality for tag checks, use the CompareTag method. Not only is it marginally faster (and can be made a little better using a TagHandle) but more importantly it throws a relevant error when a tag doesn't exist (like if you've misspelled it) instead of just failing silently
Yeah, I've tried tags, but it's like the hand physics just never do anything. They always go through the block. Like if I grab a static block that has a rigid body it triggers the explosion, but if it's just the controller, it goes through the block.
make sure you go through that link i sent, it will walk you through everything you need to check to make sure physics messages work
Hey, I tried to program a wave function collapse algorithm without a tutorial. I've got everything done except socket rotations, and it works great. Would anyone be willing to review my code? Just looking for ways I can improve, or anything incredibly stupid I might be doing. It's across these three scripts:
https://pastebin.com/1WA1ws0w - Grid Generator
https://pastebin.com/1TgW9VXu - Grid Cell
https://pastebin.com/ane5e6fG - Prefabs
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
you've already got a thread in #1390355039272439868 , there's no need to crosspost the question to here as well. just bump the thread if it hasn't gotten attention
sending a message in it will bump it up to the top of the list
wise thanks bro
vector math
Vector3 displacement = cameraTransform.right * input.x + cameraTransform.forward * input.y;
displacement.y = 0;
displacement.Normalize();```
is this equal to
```cs
new Vector3(right.x * input.x + forward.x * input.y ,0,right.z * input.x + forward.z * input.y).normalized;```
im trying to compress them into single line
why. there is pretty much 0 benefit to doing that, it makes the code harder to read and harder to debug
you can also use TransformDirection instead of manually doing the math and it will be even clearer what the code is supposed to do
nice
there is literally no benefit to that, always prefer readable code to "clever" code
oh its new function for unity 6?
no TransformDirection has existed for years, it's even in the Unity 5 docs
just turn your input into a Vector3 then pass that to TransformDirection and it will return the correct world space direction
ty👍
helloooo i have quite a problem on my hands
im trying to make a pause menu, and have made several before using this exact method b ut for some reason, it just doesent work? when I press escape, the pause menu turns on, right? though, the time scale, the camera, and the cursor script are all not doing what the code is telling it to,
the only things working ist eh UI turning on and off, the cursor stuff, and the "paused" bool. why are these things not working? i feel like ive tried everything and feel ver stupid
any errors in the console?
yes and no? I mean that as in uh, these few errors pop up once and awhile but not specifically when im messing with pause menus tuff
i also have no idea what they mean
I know those errors.. unity ones, just restart the editor
i tried that but will be happy to try again! one sec
those all appear to be editor errors so you can typically ignore them.
add some logs to your code to make sure it's running as you would expect it to
also, is it a typo or intentional that what appears to be camera is spelt wrong?
i didnt think to add the logs because i can already visually see that the UI is working as intended jjust not the stuff around it
yeah lol sorry, thats intentional
should always verify your assumptions, things that you don't expect could be happening
where should i add logs then?
inside your if statements and also anywhere that code is running that you think shouldn't be. and make sure you are printing useful info like the value of any properties you are changing or relying on rather than generic messages like "this runs"
youd hate my debug.logs lol a lot of mine are along the lines of "This works" or "This should work but doesnt" but I do understand them and what aspects dont work from the error report 😛 just funny you mentioned it
i added logs with the if statement and yeah, it says that its working as intended but its not, the scripts are stuck on enabled and the timescale isnt moving
something i found a bit ago while testing though is that, the script can turn stuff on. but, it cannot turn stuff off. say i manually disable the script and then i hit resume, it turns the script back on??
thats a very depends situation..lets say you have a box, and you have a script attached to it, and the script disables the box.. it disables the script too (so it cant be re-enabled) if however you have a script attached to another gameObject, that disables a component in the box (using same example) it can re-enable it
im not disabling its own script lol, its the pause menu script disabling the palyer script so that it cant move while paused
you can put logs in OnEnable and OnDisable and see the stack trace for what is enabling/disabling something
I may have made that mistake once or twice lol, I had to check why my code didnt run and it basically deleted the wrong object...deleting itself so thats how i learnt that error
yeah i tried that earlier and it didnt help much but i can try again
could you show me how to write it cause i forgot copletely
you just said you added logs, so surely you know how to write a log, yes?
Just to eliminate known Editor behaviors that may conflict with your setup, have you tried changing the button to something other than the escape key?
i'll try that
Escape causes the Editor to lose focus which may behave in a way you're not immediately expecting.
and my man- i kjnow how to write a log i forgot how to write that specific log
it's not a specific log? it's just a log inside of OnEnable and/or OnDisable . . .
in the OnEnable just type Debug.Log("OnEnable Method Called"); etc
if it doesnt appear, it didnt work
well yeah, i know that i just didnt konw what me meant by seeing the stack trace
then ask that instead. that's not even part of the code, that's what you see in the editor
oh my god that worked
wait- then how come ive never gotten that bug in all the other projects ive made? ive always done it the same way
the editor losing focus should not have resulted in the behavior you described
if any of the code in the if statement was executed and there were no errors then all of it would have been
The loss of focus will only apply to launching the application from the Editor so it'll be fine to use the escape key in your actual builds-release.
thank you guys so much
i was freaking out cause i have a game jam due in 2 hours lmao
I usually keybind pause to p or tab.. just out of habit I find it nicer
Hey! Having some trouble at the moment with some raycasts. Im still new to using them - this is actually my first time with them.
Anyway, whenever I am attempting to find a wall on either side of the player for a Wall Jumping mechanic. Basically, if a player is near a wall, it will output "rightWall = true" or "leftWall = true"; however, when the player jumps, it will always say leftWall = true, which messes up the rest of the code. Here is the snippet that checks for walls:
{
rightWall = Physics.Raycast(transform.position, playerObjectOrentation.right, out rightWallHit, wallCheckDistance, whatisWall);
leftWall = Physics.Raycast(transform.position, -playerObjectOrentation.right, out leftWallHit, wallCheckDistance, whatisWall);
}
And here is the full code: https://paste.ofcode.org/8SVReqU6mweFkUjWGjXTja
Any idea why this is happening? Thank you! (If you respond, please @ me. Thanks!)
Am i safe to assume 3D?
I think we’re gonna need the code for jumping.
Gotcha. Im using the Unity 3d Starter Kit, let me put the script into a paste of code real quick.
Can you show the logs? How are you verifying this?
Itll show on the unity inspector whenever I jump, no matter what I set the wallCheckDistance to. I can video that if you want
code for jumping, checking the ground, and using the new Input System
== and ||
Unless you're really intending on assigning left wall and using a bitwise OR operation
This is a shot in the dark, but it might be good to console out the name of the objects that the raycasts hit. If I was going to guess, there’s some collider that’s either enabled only for jumping or is changing shape during jumping, and is messing with your raycast
https://paste.ofcode.org/Z6PRyPpcumuTKKR4URi3Ys
The paste of code for that main jumping
Is assignment inside the parenthesis valid?
Sure but not certain about the compound bitwise OR
I dont know what bitwise means, but def was going for an or function. Guessing its || then?
Fixed it, but its still giving me that leftwall hit.
Did you save the script?
Did you fix the == also?
use the code I sent you, it will do ground check, create the Ground layer mask, allocate it in script using
public LayerMask groundLayerMask; allocate this in inspector, the variables can be changed to suit your wishes
If you assign leftWall equal to true it’s not hard to imagine why your getting the result you are getting
It was most likely both the == and ||, but this fixed it. Thank you so much!
the = was the cause of the actual issue. the | just forced it to check both sides even if the left side evaluated to true. || will short circuit which means it will not evaluate the right side if the left side evaluates to true
Oh ok! Noted. Will use || then, since I dont want it to worry about both sides if a player is close enough to one already. Thank yall so much
im abckk agaaiinnn, and im not sure if this is the right channel but when i build my game it gets flagged as a trojan because of scripts- anyway to fix this?
it gets flagged as a trojan? that definitely doesn't seem right. can you show exactly what it says?
i have had this issue before but was in Python, it was a windows anti virus issue, you have to whitelist the application
unless im mistaken the error would be "win32 trojan"
this is what happened when my friends tried to download it for a playtest
what did you actually put in the zip file
be specific
let's pretend that i cannot see your computer or project at all and that this is a beginner channel where people very frequently do things incorrectly. thinking that way, read my question again and try answering it one more time, being specific. using screenshots if you have to.
that is exactly what i wanted you to say
those are just normal build files-
so other than including the DoNotShip folder, it's correct. so unless you have some third party assets that are doing shady shit in there, it's a false positive
I mean... We can test it, dm me the folder
take that to DMs entirely if you do so as it is against server rules and any risk you take there is 100% on you
yes, do directly in dms not this server
I have a couple laptops I can test it on, it will be fine
Can confirm there's something wrong in the file, it won't even download, only anti virus I have is Microsoft's, doing a scan now, if you have any 3rd party scripts in your app, you may want to read through and delete them
i dont have any other third party scripts no
Then it's a conundrum, I'm running on a special network that's not connected to any device but my own laptop. It's a personal WiFi, so when Google stopped it, Microsoft also did, recommend re reading your program and ensure nothing gathers system data or reads anything from system
how do i check that?
I'll DM you
Follow up @slender nymph just in case anyone else wanted to know, it was seemingly couple lines of script that were wrong, deleted them and they worked
hi guys :)
Hi all, is there any specific channel for modding unity games?
Good Morning pepole i am look for an good Unity coding basics tutorial does any one have a good tutorial?
modding discussions are not permitted in this server #📖┃code-of-conduct
there are beginner c# courses pinned in this channel and the pathways on the unity learn site are a good place to learn the engine
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Is that for me?🙂
If yes so yes im talking about ui buttons and need to make them for movement controller
hey i want to make animation which engine should i use
for begiiner
for cutscenes
you don't need an entire engine to make animations..
also this is a coding channel
but i am making game in unity
Please reply me next time because i didn't know if you responded or not🙂
So I just need to make buttons now left right up and at the end i need when button get down and up for that to make it like hold click and when leave button you understand me i think so how should i do it in same script?
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
if i want to make a hitscan weapon wider than a typical raycast, what methods do i need to use? if someone could point me in the right direction with this i should be all good
i'm thinking something like the charged revolver in ultrakill
or railgun
Spherecast (3d) or circlecast (2d)
that would make sense actually
are there any ways to display those visually, like Debug.DrawRay does for raycasts?
could do 2 offset drawrays
Not out of the box but there are assets for it, or drawing the outlines with a bunch of rays is usually good enough
alright
feeling a bit lazy for now and i can do graphics stuff later so i might stick with a drawline between the start and end
is there a way for me to make it return more than one collider, or go infinitely?
Pretty sure vertx had some visual debugger
#💻┃code-beginner message
SphereCastAll and CircleCastAll
thank you very much
i'll add a raycast at the start to check for where the shot hits a surface, then do a CircleCastAll for enemies between the start and the end
im trying to read a text that should come with the game
i attempted this, then found out that unity apis can only be used on mainthread?
Task.Run(() => Resources.LoadAsync<TextAsset>
i suppose i can switch to traditional file io but idk if resource folder destination exist after build
how can read the text without blocking the game ?
[SerializeField] private TextAsset file; and drag in the file as usual. The contents are in file.text
no, i need to load the level datas, it created alot, i want to load specific one
Serialize an array, put all of them there, read from the array
this kinda sounds like an xyproblem
The levels are just in a text file?
i want to load the text file that should come with the game, without blocking the game ?
I could be mistaken but in your initial comment your using a pretty generic file handling function when unity has some more tailor made json parsing utils
just a quick google on async json parsing unity has some interesting results
json from util? but i still have to access and read that entire text file right ?
So do you have one file or multiple? If you have "the file" then why can't you treat it as a normal asset like everything else?
wanting to load them from a arbitrary file explorer location seems like a reasonable request in general though
So when you said "the text file that should come with the game" you meant "the text fileS" as in multiple?
yea i think thats sound right
And if you have multiple why can't you do this
and choose specific one
i dont think thats a good solution, anyone feel thats way?
do i just keep 500 text file on that array?
i want to only load wat i need
i agree that that doesnt sound ideal
Unless the files take up several megabytes, the simplest solution is the best
hmm i thought this problem is common
i guess i can throw it a loading screen let it freeze a few sec for now
If needed you can get the text/bytes from the asset first on the main thread and then parse on another (e.g using json.net)
but if efficiency is important then json should be replaced
do addresable help?
just an alternate way to load the assets. I dont know if that forces main thread usage
or use streaming assets to load the files with non unity file io
alr sound like there still a lot to try
i've done addressable loading in webgl which works meaning it is single threaded loading unless there's more options I've not really fooled too much with
well that could do some alternate time sliced loading specially for webgl but i guess its quick to try to use the addressable api on another thread
gonna be a few days for me fr need to see guides never touched addresable
I've used it a lot so ask in #📦┃addressables if you need help. It uses asset bundles so this means asset dependencies can be duplicated in some situations. Read the docs carefully
when using a raycast to find all objects between two points, is there an easy way to have the returned list ordered by distance or will i have to do a bubble sort on the returned list?
You have to sort it yourself but you don't need to implement your own sorting algorithm, Array.Sort is much faster than bubble sort
or List.Sort
oh alright
how do i sort it by distance if all the objects are RaycastHit2D
or should i not be doing that
the unity docs says Array.Sort() is javascript only but i don't know if it's outdated
result.Sort((RaycastHit2D a, RaycastHit2D b) => a.distance.CompareTo(b.distance)); (untested)
You're looking at some ancient version's documentation. In any case collection sort is pure C#
Hello
[Conditional("UNITY_SERVER")]
private void StartServer()
{
networkManager.ServerManager.StartConnection();
}
Where can I find a list of all the conditional strings I can use?
Is moving platforms hard
the conditional strings are defines in the build settings
depends entirely on your game and what platforms are involved
Here?
Player settings -> other settings -> script compilation
Just a square that can move and its a game where you climp up a giant tunnel because im new nothing to special
unity defines some for version, and if you are in editor aswell
You can find info here: https://docs.unity3d.com/6000.2/Documentation/Manual/platform-dependent-compilation.html
Oh "platforms" usually refers to pc, ps4, mobile 😄 i was confused
That sounds like !learn would be the right resource for you
uhh i think the bot is lazy
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
<@&502884371011731486> crypto scam i assume, they didnt even manage to link the images right
?🙂
Is transform what i should use
In the code
if you want jumping mechanics rigidbody/playercontroler is what you are looking for
Can you reformulate that question a bit clearer? No offense but I think I had a stroke while reading that 😄
So how do i move gameobjects im confuse
You should really look at the learn link above, that is basic unity knowledge and that page teaches it to you
Ok
Aaaa What didn't you understand?
Are you a cat?🦔
Honestly i cant make sense of that sentence 😄
I mean, what did you not understand from the question in the previous message?
Yes
punctuation is a blessing...
The whole question is just a scramble of words that dont make sense
Umm wait
Now you know the ui buttons to make the character move right?
Right &left &up 🙂
So no?
I'm tired of explaining this. You can go back to my last messages, I think.

You mean a the built in onscreen joystick?
Well make your own, put buttons on the screen and map them to a script
There is no built-in solution for that
Yes im asking about how can i make get button down and up for specific button in same script 
You can map each button to a different method in the same script
Do you have an example?
This is a coding channel and not about how to setup a UI, just to remind you
Im not asking for build code
Just ask for example for make status for each Buttons in same script
Almost nothing else about it.
Onclick
Just one click
I've seen almost all of these things.
So no comment

Start typing full sentences with ponctuation, so people know what you want
Bro im really dont know what should i write else i think all understood what i mean really 🙂
well, you have been told otherwise just some minutes ago
But he understood at the end
And when I asked before, he didn't tell me that he didn't understand, but I asked for an example of how this is done, and I haven't received one yet. So..
your attitude is one of a kind. Im stepping out as well as the person did before for good reason. I gave you the solution for mapping to a button via script. Now its up to you to do your job.
Ummm you send me onclick and its will make character Either move once or continue moving until something happens, and in both cases I will need to place a command if the button is get up so
Hope you understand
yeh, welcome to how to use unity documentation. Get on the button class and read the documentation what other options there are, that could help you.
If you dont start to get the habit of reading documentation at all, you gonna have a hard time in the future
Didn't find what i need i think so thats why im asking
And what did you search for?
All told me yes you can buy no one send something 🙂
Onpointerup&down
But do script for Each button individually
Im out
And wait for other one
And that is your biggest issue, you keep waiting for others to do your job
I think stack overflow will help
When someone get issue and he doesn't know how to solve it he should ask right?
And i didn't find anything else so thats why im asking now
So if anyone else knows how I'm supposed to do this I'm waiting to hear back.
Going forward, if you're going to occupy this channel as much as you do currently, please start using threads. Thanks.
i just tried this, it seems promising but i'm getting an error message:
"Cannot convert lambda expression to type 'Array' because it is not a delegate type"
i'm not good with lambda expressions so i don't really know what to do here
sorry for taking a while, i had a lesson to go to
Hey, is there any point is assembly definitions if 2 of my scripts need to talk to each other?
Afaik Assemblies are meant to be 1 way right?
Do I need to look into ways of fixing my scripts that will only work 1 way or create a manager class that would let them talk to each other?
Try Array.Sort(result, (RaycastHit2D a, RaycastHit2D b) => a.distance.CompareTo(b.distance));
should i replace array with the name of the array? i would have thought that would be what you mean by result
sorry for my incompetence
No, replace result with the name of the array. It's a static method
oh
now it's saying the name 'Array' does not exist in the current context
do i replace it with Type[]
(obviously not verbatim)
Array with capital A
add using System; at the top
hello! Anyone have idea how to fix this "item scratch bug"?
"item scratch"?
stretch I assume
when the item is parented on picking it up, make sure all of the parents have uniform scale
stretch* am sorry
private void PlayExplosionEffect(meleeEnemies enemy)
{
Instantiate(explosion, enemy.gameObject.transform);
}
I tried using this to spawn an explosion gameobject with an animator to play an vfx on an enemy
but nothing is spawning? what could be issue?
I see the object in the hierachry but no visual
check the object, see if it has all the necessary renderers and they're all enabled and have assets set etc
Happens when you rotate a parent object of something that has non-uniform scale
ye looks like that the issue, how do I fix that?
In general, don't use non-uniform scaled objects.
If you need a rectangle, model a rectangle instead of stretching a cube
I modelled it in blender, its my own
imported into unity, added a rigidbody and box collider on it and thats it
If you didn't change its scale in Unity then it doesn't have non-uniform scale
i did
Do you know what we mean when we say "non-uniform scale"
What's the scale of the object?
What does "basicly" mean? Is it or is it not that?
it is, from every perspective
Lol hilarious bug, looks almost as though it's transforming it's size based on your input and movement
And what's the scale of the parent?
I just want to confirm my understanding, trees and other objects place in the terrain cannot be interacted with like chopping them down, correct?
if its a vfx either set play on awake to true or reference the particlesystem and execute .Play() on it
parent?
When you pick up the object, you parent it to another object. What's the scale of that object?
It's uniform so not the issue. Are you sure you parent it to the capsule and not the camera?
Does the object become a child of that capsule? Or does it become a child of hold position which seems more like what you would be doing
Show a new screenshot while playing after you've picked it up
If it doesn't become a child of holdPosition you should honestly consider renaming that object
now you say, i check them
Easiest solution, upload your code, it may well be an issue there rather than anything else
there u go
commented literally everything cuz i finished last night plus ai helped abit
heldObjRb.transform.parent = holdPos.transform; //parent object to holdposition
i think ya found the issue
Why is it that when I reload the scene, the ui buttons stop working?
after deleting the line, its fixed but the item isnt like infront of me
The code is not the problem.
I made sure to only reference to objects that are static and are in DontDestroyOnLoad
Put that line back and check that:
- holdPosition has uniform scale
- Camera has uniform scale
- CameraParent has uniform scale
- FirstPersonController has uniform scale
the first person controller was like 1/2.3/1
now everything works
after setting it to 1/1/1, but now my character is too small 
Took 40 minutes to get to where we started 
am on the ground
welcome to coding lol
ye, drop your paypal
well make the character bigger
you have to change the positions now that the scale has been fixed
if you want to change tranform of an object independent of its parent use the .localPosition and localScale etc
Are the buttons themselves in DDOL?
Yes
The issue is rotating an object with a skewed parent. That's not something that can be solved in code
so now i dont change uniform scale
but how do i make it taller without the gravity making it small again? 
Can you show the inspector for the button
This is first person right? Just make the camera higher off the ground
Maybe change the size of colliders if necessary
You can change the capsule's scale to whatever you want if it doesn't have any children
Can you double check your Event System doesnt get deleted
works, hellyea
What event system>
now i have to figure out how to do the playercamera to now see the capsule and its shadows
oh this
When you add a Canvas, it automatically adds EventSystem in your Hierarchy, this handles UI Input calls, when you refresh, in your hierarchy, where it says Sample Scene make it show all items and check to see if its deleted or not by mistake
it's not in DontDestroyOnLoad
It doesn't get deleted when the scene reloads but it's probably not the same one?
I'm not sure
Can I make it a child of the UI gameobject?
As long as you have one eventsystem active its fine
sure
okay, so that possible issue seems eliminated, have you checked that all the scripts are attached after the reload happens and they dont get deleted from the gameObject in the process
But wouldn't I still see the hover effect?
I don't even see that when I hover over the button
public void RejoinServer()
{
string currentSceneName = SceneManager.GetActiveScene().name;
SceneManager.LoadScene(currentSceneName);
}
Is this how you're supposed to reload a scene?
I dont see why youd want to stop and restart the client...
I shouln't have included that, it's unrelated
I figured it out
It was the fact that the Cursor was set to Locked mode
In the editor it can be in locked mode and you can still see the mouse sometimes
And in that state the UI doesn't work
well that works lol, either way one other way of using the Load scene is LoadSceneAsync which I was going to show but forgot the formatting command for code
thanks alot for the help btw
Seemingly random it sometimes instantly dissapears instead of fading out (the "if health" is in another part of the script ive just put it out for this text)
if (health <= 0)
{
c = sr.color;
InvokeRepeating("FadeOut", 0, 0.01f);
Invoke("Destroying", 1);
}
private void FadeOut()
{
transparency -= 2;
transparency = Mathf.Clamp(transparency, 0, 255);
c.a = transparency / 255f;
sr.color = c;
}
private void Destroying()
{
Destroy(gameObject);
}
Have you tried calling your Invoke("Destroying", 1) from within the FadeOut() method
no but how would i do that
There is nothing preventing the FadeOut() method from being invoked multiple times. If your check for health <= 0 happens in Update than every frame you call InvokeRepeating(). Better to use a Coroutine
im checking the health in a a seperate method thats only being called if the health gets decreased
so the fadeout only gets called once
c#
private IEnumerator FadeOut(){
transparency -= 2;
c.a = transparency / 255f;
sr.color = c;
yield return new WaitForSeconds(2f); // Change the 2f to a suitable
}
What if two objects hit this one in the same frame? Wouldn't that call the TakeDamage() method or whatever it is called twice? I recommend you add a bool 'isDead' that gets turned to true once the health drops below 0 for the first time.
i havent thought about that thanks
also dont forget the clamp line..I forgot to add it, but general gist of a coroutine
yeah, thank you!
also make sure you disable colliders and stuff like that for the one second between being killed and despawning. Or alternatively, disable the object instantly and spawn a "dummy object" at the same position that fades out.
already have done that ive made the rigidbody static and destroyed the collider
Destroy already has a second parameter for how long to wait before destroying. You don't need to use invoke to delay it
why not make this a loop
ive done now
private IEnumerator FadeOut()
{
for (int i = 0; i < 125; i++)
{
transparency -= 2;
transparency = Mathf.Clamp(transparency, 0, 255);
c.a = transparency / 255f;
sr.color = c;
yield return new WaitForSeconds(0.01f);
}
Destroy(gameObject);
}
I mean, I used his code alone, but theres a few ways to do it, ill include how I did it
Also how did you get that cute box for the code
float elapsedTime = 0;
while (elapsedTime < TIME) {
elapsedTime += Time.deltaTime;
c.a = Mathf.InverseLerp(0, TIME, elapsedTime);
yield return null;
}
this is a very handy pattern that you should get accustomed to
use ` 3 times at the start and 3 at the end
this also lets you specify the duration it takes
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
see the lower section
makes sense tysm :D
public IEnumerator FadeOut(float time)
{
while (canvasGroup.alpha < 1f)
{
canvasGroup.alpha += Time.deltaTime / time;
yield return null;
}
}
public IEnumerator FadeIn(float time)
{
while (canvasGroup.alpha > 0)
{
canvasGroup.alpha -= Time.deltaTime / time;
yield return null;
}
}
wrong thing
just be aware that the WaitForSeconds isn't perfect, it waits equal to or greater than the listed time
` not '
lol azerty keyboard
now be careful, the canvasGroup cannot go past 0 or 1, but sometimes the variables can, so clamp values and do checks, any comparison against a float variable can pose issues of precision
any comparison against a float variable can pose issues of precision
not necessarily - it's equality checks in particular that may have issues
I found out the error it was also another script not just this 🥀
it's like a gameobject with a canvas renderer on it
also StateBehavior.OnStateExit() Does it execute on the last frame of the current state, or when the state is actually exitted?
If it helps any, I designed an entire system for dialogue and questing, rewrote it from about 10 scripts down to about half... And had that many errors I just put on pause, the code works it was just the reformatting everything and setting the variables again (from scriptable objects to entirely code)
no the error was that it tped the object at the wrong time sometimes thats why it was invsible 🥀 i was stuck so long and it was just an bool i checked wrong
Hey, I was wondering if there's a way to make this curve be linear or sm by default, kinda like what unity usually does by default in the inspector:
public AnimationCurve Curve;
Since this is a struct, I tried this:
public CameraAnimationSettings(float duration = 0, EasingType easing = EasingType.Linear)
{
Duration = duration;
Easing = easing;
Curve = new(new Keyframe[] { new(0, 1), new(1, 1) });
}
But it sadly didn't work, it gave me a (1, 1) (1, 1) curve.
Please @ me and thanks in advance!
Thanks.
And I just assign it in the ctor, right?
you would assign it on the field
I am positive you can't assign to fields in structs, am I mistaken?
hey I'm trying to destroy an Object once this state has cycled through itself once, I thought this would be work but the OnStateEnter works but OnStateExit doesnt, I thought it would be called ont he end frame of that animation?
oh yeah no you're right (at least with the version unity has)
I mean, I can just switch to a class, no big deal in this case
that's the mechanism for default values afaik, so.. im lost
not really a code question, but wouldn't OnStateExit be called when the state actually.. exits, not when it's done
perhaps add a transition to End with exit time 1
that works, thanks!
why does it spawn one with Z=0 , and the rest Z= 180 lmao
Because Quaternion is a four-dimensional complex space number and the values you've given it are absolute nonsense
If you ever find yourself modifying the individual values of a quaternion, don't.
oh I always assumed they were the rotations
well, they are, but not in a format you'll understand unless you're a mathematician
they aren't euler angles
valid quaternions are normalized as well
Yea that constructs a Quaternion from Euler angles which is much easier for most of us to understand
They are, but they're in Magical Wizard Numbers that have nothing to do with degrees or the normal axes of euclidian space
I updated from 2022.2 to 6 (Yes I know) and my tileset won't show, anyone has pointers?
like, I get the outline, but not the tiles themselves
Make sure you are using correct renderer and matching shaders
how can I check this?
You can create a new scene and compare against default components
Oh, I got it now, and it works just fine, thanks!
are there any easier ways to make an object move based on the players position? cuz the code I'm using rn is really clunky even if it's just covering the X axis
the code in question btw --> https://paste.mod.gg/tvqhmxmgtlpt/0
A tool for sharing your source code with the world!
holy shit you're doing a Find of the player every frame and Rigidbody Get?
why not cache those in awake once and reuse them
anyway, did you try just moving the transform itself and see if same thing happen? if it doesn't then it could be rigidbody or like interpolation issue
wdym there are no issues
Personally I would use a better solution for an enemy, if they're meant to move around the map I would combine A* / Navmesh agent with a bit of strategy to move it from point to point (if its within range of player then you could do a local strafe)
I'm just asking if there's a more efficient way of doing it
the code technically "works" fine
I mean it looks choppy between movement
It's doing kind of the reverse of what would be natural. The closer it gets, the faster it goes. Usually it would do the opposite
Now it speeds up and suddenly stops when it reaches the player which causes the choppiness
You could try something like this:
float distance = PlayerBody.transform.position.x - transform.position.x;
rb.linearVelocity.x = distance * speed;
which would make it slow down when it gets closer
(I don't remember if you can change velocity.x directly)
var vel = rb.linearVelocity
vel.y = distance * speed;
rb.linearVelocity = vel
yeah that
Ridibody2D has rb.linearVelocityX and Y dunno why we dont have it for 3D shakes fist
to be fair, all that does is new Vector2(value, rb.velocity.y), can easily create an extension method to do the same for 3d RB
tru tru..
it would just take unity like no time to implement an extra property when they added linearVelocity but who knows why they didn't
Any vscode users getting auto-generated 'GlobalUsings' files?
Its throwing a bunch of errors for me for one specific script, and there are no changes on my .git aside from the obj.meta that keeps reappearing
Not sure what extension is causing this
Seems like a recent update thing
I use VSC but never seen such an issue :\
This is so annoying :(
are you sure it VSC causing it ?
you tried just flushing all cache? delete the Library folder and all that already?
Yeah, seems to be the case
Still waiting for them to remove camera and rigidbody etc properties from MonoBehaviour. Apparently that would be a major breaking change but renaming velocity to linearVelocity isn't 
I also have this project on my laptop that doesnt have vsc installed, and the editor has no issues
lmao exactly
Might do a clean reinstall of vscode
ohh thats strange.. did you add any extra extensions that would cause such a thing
Nah but i've noticed it has been gradually adding extensions on its own
Intellisense is different, autocomplete has changed, its annoying
All I want is the C# tools to see references to everything
really ?
my autocomplete (intellicode) hasnt been working for a while.. just intellisense
maybe its the new c# update? now Im scared to update it lol
Yeah it keeps suggesting things based on patterns instead of if they exist, methods, objects, etc
ohh...hmm I would check your extensions, doesn't sounds standard
gonna clean reinstall yeah
weird...I have intellicode but seriously it worked like once I think half a year ago.. it havent wokred since..
Can someone please tell me how to make a slide mechanic using unity's visual scripting
Don't crosspost
mb
#1390346878394040320 probably?
i did
nobody gives darn about visual scripting though
try code scripting
That's the trap of visual scripting. It seems easier, but when you hit a wall, anyone with the skills to actually help are just using real code
mostly designers
my monkey brain can't learn or just keep info that i learn to use it
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
try this
All the hard parts of programming are still there in Visual Scripting. If you can use that, you can learn code
The syntax isn't the hard part
once you learn the syntax, its just like writing a pargraph / sentence
IDE will basically be ur spell-checker in real-time
just need to know how to structure the words
instead of a bunch of arrows going all over the place.. the code has benefit of hiding your spaghetti visualy at least xD
virtual spaghetti
ma spaget!
mom's spaghetti
There must be a better implementation for slowing down the player when he charges up a weapon (in this case, a sniper-like weapon). Please help
PlayerMovement has a few blocks of code responsible for that
This is in the Update method (weapons is a list of all the weapon game objects):
https://pastebin.com/G4XN75d0
Those are the methods in the PlayerMovement script:
https://pastebin.com/ec4Lku4e
And this is the Sniper script:
https://pastebin.com/GPtknJQG
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
code is heavy.. moms spaghetti
my brain sees code and thinks nah it's too complicated
whats calling SlowDown
its pretty simple
u use a speed variable for ur movement
u adjust that speed variable depending on which weapon is equipt before using it int he movement
speedVariable = 10 if no weapon;
speedVariable = 5 if big weapon;
Move(direction * speedVariable);
Whatever weapon you're holding doesn't change your speed. What matters is the state (is charging up, is not, etc)
oh.. well same thing can apply to that too
appearances can be deceiving...believe me...I used Game Maker for a long time because code "scared me" but I jumped into unity and learned c# ... it was not that hard lol
Is there a way to reduce a boxcollider2D from the top instead of it being reduced from both below and the top? I'm asking that because when I crouch, my character doesn't go from IdleState to CrouchState for example, but from IdleState to AircrouchState to CrouchState, since it's briefly in the air (because of the raycasts that detects the ground) before the offset takes effect.
so where should i start
Move(direction * speed);
little trick.. use the rect-tool
basic c# stuff you know..syntax, writing variables etc..
once you start getting those then worry about Unitys API stuff like components and Monobehaviors
its a giant puzzle you dont slap all the pieces at once and expect a picture.. You build it piece by piece
also here's how far i got with v.s
that may not work for 2D tho...
dont do colliders already have their own gizmos?
just in case u can click the Edit button in the inspector and do the same ^
☝️ yeap mb
try this maybe https://learn.unity.com/pathway/junior-programmer
u can also do it manually by hand in the Size and Center/Pivot slots in the inspector
so where do i start like what website to learn from
do a bit of both.. microsoft site + unity learn
unity learn kinda expects you to know a bit of basic c# last time I checked maybe they changed it?
the one I linked starts from 0 knowledge it says
i did crash course like this ^ to understand the basics... and then i just jumped off the deep end
for Unity
for example it gives you this
but doesnt explain about how to structure code, variables , ddata types etc
something just like this is complicated for me
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float horizontalInput; // Stores input from left/right (A-D or Arrow Keys)
void Update()
{
// Capture horizontal axis input every frame
horizontalInput = Input.GetAxis("Horizontal");
}
}```
because there are multiple pieces, but if you break it down (knowing the syntax)
it looks less intimidating
it doesn't make sense until u start trying to work with it urself..
i don't even know what you just typed
u can look at it all day and it doesn't do u any good until u start trying to do it urself
Okay, but, like, why?
You already know the concepts of functions and variables from visual scripting
This is just that
Code isn't magic, each word means something
ik variables but not functions is that like nodes?
its literally
psuedo code then turned into real code
PlayerController.cs is the script <- goes on a gameObject
public float horizontalInput <- is just a variable of type (Float) that stores a value..
Update() <- a built-in unity function that runs once every frame
soo every frame
the code sets horizontalInput to whatever ur computer is grabbing from the Input.GetAxis("Horizontal") which is just ur W/S and Up and Down arrows (traditionally)
You already know the concepts behind the words. If a French person points at a grapefruit and says "Pamplemousse", you can discern that what they've just said is the word that means "Grapefruit"
Surely Visual Scripting has some concept of "Update"
How do you get something to run every frame in Visual Scripting
on update event
https://docs.unity3d.com/6000.1/Documentation/Manual/event-functions.html
In Code, you can specify those functions and put stuff in them. Unity runs those functions on every script that has them in the scene
So, you know how to set a variable, and you know how to make something run in Update. That's literally all this block of code is doing.
good to start small like that..
and importantly, in a couple lines instead of a bunch of blocks and arrows going all over the place
maybe make two numbers add up and display itself in the console 💪
the basic c# projects, calculator is always a good start to get the basics
float a = 1;
float b = 2;
float result;
void Start() // <-- another Unity function runs when the game Starts
{
MyAddFunction(); // <-- call the function below
}
void MyAddFunction()
{
result = a + b;
Debug.log(result); // <-- prints it to the console window
}```
no?
seriously I miss the purple already 🙁
StrangerDanger!
wasnt like Unity employee badge this blue?
why is it blue now anyway
ya but they upgraded to Gradients 😉
they changed the color of the Asset Publisher role
thats all
damn
Why no?
Add(double a, double b) 😉
edgy
a float based calculator scares me
he'll swap it for int im sure of it
aww shit..division will break it 🙁
part of the learning process 💪
fr..why is 3/2 = 1 🙁
how would i come to the conclusion of them saying grapefruit? like if a Japanese person came up to a car and said これを見たらあなたはバカだ i woundn't think they are saying これを見たらあなたはバカだ
ur procrastinating already
well the whole "points at a grapefruit " you can deduce it visually at least
indeed i am
You know if you are utterly incapable of discerning meaning from context you probably shouldn't do game development
Hello everyone! I'm having some trouble working with the Addressables package, I'm running VRChat Creator Companion with VRChat SDK 3.7.6.
These are the errors I'm getting:
Library\PackageCache\com.unity.scriptablebuildpipeline@1.21.23\Editor\Tasks\CalculateAssetDependencyData.cs(126,30): error CS0117: 'ExtensionMethods' does not contain a definition for 'ExtractCommonCacheData'
Library\PackageCache\com.unity.scriptablebuildpipeline@1.21.23\Editor\Tasks\CalculateSceneDependencyData.cs(89,30): error CS0117: 'ExtensionMethods' does not contain a definition for 'ExtractCommonCacheData'
Library\PackageCache\com.unity.scriptablebuildpipeline@1.21.23\Editor\Tasks\CalculateCustomDependencyData.cs(91,30): error CS0117: 'ExtensionMethods' does not contain a definition for 'ExtractCommonCacheData'
Library\PackageCache\com.unity.scriptablebuildpipeline@1.21.23\Editor\Tasks\CalculateSceneDependencyData.cs(157,82): error CS0117: 'ExtensionMethods' does not contain a definition for 'FilterReferencedObjectIDs'
Library\PackageCache\com.unity.scriptablebuildpipeline@1.21.23\Editor\Tasks\CalculateSceneDependencyData.cs(198,67): error CS0117: 'ExtensionMethods' does not contain a definition for 'FilterReferencedObjectIDs'
Do you guys know anything I could do in order to fix it?
!vrchat
Join the growing VRChat community as you explore, play, and create the future of social VR! https://discord.com/invite/vrchat
you could try the ole
Shutdown Unity
Delete the Library folder
Re-open Unity
im going to actually try to learn this and will get back to yall when i Inevitably quit or when i need some motivational words
The funny thing is in Japanese context is very important in speech 😅
Welp I guess that I'll go there, but I came in here since Addressables is not a package used for making VRChat avatars
Thanks for the info tho o/
take your time, and dont rage at yourself if you're not picking it up right away, the initial burn is much quicker but it rewards you later to that feeling of " wow was it always this easy ..wtf"
best we got.. unless its something specific to the VR packages and stuff
which VRChat would know more about
ahh, the ole' im a dumbass moment
Yup it must be it since they removed these calls in newer SBP
You guys have a great day alright? :)
seriously in game maker I did everything with drag and drop because I thought GML(game maker language) was too hard...then I learn something (arguably) harder and suddenly I felt so silly..lol
Alright did a fresh install and it has only these extensions.
Still getting weird auto-generated globalusings files
i just cringe at complete drag and drop work-flows
should script u something that tells u the "Distance" in miles/km that ur mouse travels to do a specific project
it was basically components / nodes like scratch you can attach to "gameobjects"
you just typed in numbers, timers and all that were just premade "components"
I started as artist mainly, code was very intimidating at the time
did it come with the puzzle piece tabs to keep u from dragging things that dont belong?
sadly no and had to learn the hard way haha
fun fact.. the outward bits of a puzzle piece are called "tabs" sometimes called knobs
and the inward bits of a puzzle piece are called "blanks" sometimes called holes
i love trying to find fun words and descriptors to use in my scripts, im on TX -> RX system right now..
but Tabs -> Blanks could work..
basically I felt familiar with Game Maker because I learned on Klik & Play ❤️
noo Game Maker was a game engine
well still is but now its more "modern"
ops it was small
first to three in process of elimination reg scripting won
yup, if thats how u make decisions.. Visual scripting is probably best
its process of elimination
regardless the concepts are pretty much the same
components too..A Rigidbody is a rigibody no matter if Visual or Code
Best out of three
Mine says u should keep visually scripting as well
using UnityEngine;
public class DecisionMaker : MonoBehaviour
{
public string Option1;
public string Option2;
[Header("Decision")]
public string Decision;
[ContextMenu("Make Decision")]
void MakeDecision()
{
if(Random.Range(0,2) == 0)
{
Decision = Option1;
}
else
{
Decision = Option2;
}
}
}
The biggest Unity game of the year so far is heavily reliant on visual scripting, it has it’s place
except my version i can create artificial biases 😈
bool shouldIDoVisualScripting = Random.value >= 0.5f
or put the odds in the favor of code bool shouldIDoVisualScripting = Random.value < 0.2f
public float Bias = 0.5f;
if(Random.value < Bias)
{ ...
which one?
Silksong
oh i had no idea that was even made with unity
😛
Silksong and Hk use a ton of Playmaker for enemy ai and general level design logic afaik
huh..where is that mentioned?
naughty naughty 😆
people think the only unity games are the bad ones with "made with unity" at the start 😔
mostly the idiots who think every game is made with like unreal
Okay every time I try to open vscode through a specific file it generates all this stuff, in this case, i opened Billboard.cs
Its definitely the c# extension doing it because it says "restoring Billboard.cs" in bottom right
Something is also causing vscode to lag everything else out, trying to disable ai features
this is a .net project not unity tho?
This is the same project ive been working on since 2021 with no changes
ohh.. why is there a .net 10 core folder?
No idea, it appears after the corner dialogue says "restoring <filename>" when extensions start up
fresh install, only these 4
weird.. could it be your .csproj /sln in your project are messed up or something ?
maybe
have you tried other projects / blank ones? is it just this?
I'm not using any special dependencies, just this
weird..no idea what those folders are .. mine just shows /Assets and the Solution Explorer
yeah it generates inside of whatever folder my script is
weird..
you tried another project?
(there's a word for it btw, "regression")
Its happening in other projects too :/
Still happening, lags the hell out of my pc
well shit...maybe clean install VSC? I have no idea what it could be
Yeah thats what I did,
this only happens after installing latest extensions, folllowed these instructions https://code.visualstudio.com/docs/other/unity
hmmm I guess thats when you last updated it, but update came out in august
Had no issues last week
so rollback to 1.1.2 ?
whoa im behind
What are you on?
thats the Unity extension not VSC version btw
ohh thats what u mentioning
Im trusting that OP says updating the Unity extension started problems lol
yea im good
Haha yeah, made no progress today due to this
yeah thats the latest
i did have a never-ending loading bar yesterday
made my entire pc laggy... but a restart fixed it
I uninstall as soon as any traces of Github Pilot are mentioned
yeah intellisense gotten a bit slower lately
I think they added something that caused a slower startup...
reminds me VS days
yeah once it gets going is non issue. I usually got 4 different Unity / C# projects open
What do your external tools settings look like?
I unchecked embedded and local packages to see if that would fix, no change
did you delete the old csproj and .sln and try hit Regen?
trying now
one time i had to do that when I renamed my project / folder
The project did change names earlier this year
even when project was a Visual Studio project it was all weird..so I just deleted and refreshed
worth a shot..there could be lingering sln/csproj from old name causing ambiguity or something
Took me a while, is this a good implementation?
in Update in PlayerMovement
var weapon = activeWeapon.currentWeapon;
if (weapon != null && weapon.releasedButton && weapon.isCharging)
{
SlowDown(0.3f);
}
activeWeapon is referencing the weapon switch script
public SwitchWeapons activeWeapon;
currentWeapon is a property in the weapon switching script
public Sniper currentWeapon
{
get
{
if (weapons == null || weapons.Count == 0) return null;
var weapon = weapons[selectedWeapon];
return weapon != null ? weapon.GetComponent<Sniper>() : null;
}
}
It still feels like spaghetti
Although it's a thousand times cleaner too
there could be some possible issues
selectedWeapon index must be accurate .
repeated GetComponent calls when you could just cache it
How to implement memoization in here?
It's a property
Not all objects hold the Sniper component
maybe only do it if the index changed from last time
also not sure I would put any movement control in a weapons / weapon switching script
doesnt scale well. I would use an event and listen for those in a separate script that controls the player move speeds
weapon should not care about the player, what if you want to add a weapon to other entities? or want to only affect specific movement (player has a buff that removes slowdown for charge etc..)

rips off beginner-programmer disguise and dives into pile of empty monster cans
ah so it was C# Devkit not unitys..interesting..
Its 2:41pm, I can now get started for the day
On what I was talking about earlier in #unity-talk I've seen these examples all over the Internet that don't appear to work anymore (maybe Unity changed over the years and it's no longer possible). They claim you can call a method in another gameobject this way.
...you can
that still works fine
That's completely allowed
You were specifically asking for solutions that didn't involve dragging in references
They are saying in these examples that it doesn't.
That what doesn't
That you only need this code and nothing else is involved
That was never the case
thats a big fat lie wtf 😐
At any point in Unity's history
You would have needed to drag an object into the inspector to do this in literal Unity 1.0
You have to tell it which ScriptB you want to call DoSomething() on
maybe some type of reflection or Broadcast Message ?
Animation event is a wierd one, if you don't select the same animation from specific animator it doesn't let you use a dropdown and you have type a string for method
What would cause a type mismatch when you attempt to drag another gameobject that has the script attached using that example above?
putting a scene component in a prefab
Does the object you drag into that field have to be a prefab?
you can have prefabs or not in scene component, not opposite
they are assets and can only contain other assets
Are you using scriptable objects by any chance?
I just have an object with a sprite sitting off screen to attach things to (currently "ScoreHandler" script). And tried to drag that over.
prefabs cannot reference objects in the scene because objects in the scene only exist while the scene is loaded but prefabs basically always exist. you can't have quantum references
so prefabs can only reference things in themselves or other assets. scene objects can reference anything in the scene as well as assets
if you need something to already have a reference to a scene object when it is instantiated from a prefab then you'd pass the reference when the object is instantiated
https://unity.huh.how/references/prefabs-referencing-components
When I decided to create scripts that wouldn't actually be "seen" (on an object) I just placed a sprite off screen to attach scripts to so I can use the scripts
If it's never going to be seen why does it have a sprite
you do know that a component can be on a gameobject that doesn't have a renderer, right?
It's just kind of a visual reference to what that object is used for (currently a folder)
hell if you really want visuals put the included icon, at least it lets you put proper visual and not something that then you have to hide offscreen
thats why these exist
Wasn't sure how else to use the scripts because they didn't need to be on anything in-game that was spawned or might get destroyed
Just put them on an empty object
^ if its a monobehaviour then its a component and needs to be on a gameobject to run.
A game object consists of a transform at minimum, digiholic is correct, an empty game object is great for manager type scripts
quick question, in the junior programmer course, this script is brung up.
" Instantiate(obstaclePrefab, spawnPosition, obstaclePrefab.transform.rotation);"
so can I use this same idea to get the same rotation, and position as the original prefab?
yes you can use the original prefabs transform values
Quaternion.identity is also an option
and to add on to this, if it doesn't need to be a component (i.e doesn't need Update messages) then it could just be a scriptable object instead. or even a poco constructed by some other monobehaviour
If you want to use the values from the prefab, simply don't include them in the function
if they're not provided, it will use the prefab's values
Im assuming Quaternion is the prefab in question?
tyty
Quaternion.identity just means no rotation
Quaternion is a type of rotation calculation, but it takes on the base rotation of your prefab
Oh thanks for telling me thats sick
Quaternion is the type that unity uses to store orientations. It's the type that transform.rotation returns
and before you try it, don't confuse the axes of a Quaternion with euler angles (angles in degrees) because they aren't and should not be used that way. you can however construct a Quaternion out of euler angles using Quaternion.Euler
^^ almost always work with Eulers for your sanity
if you want to know how quaternions work.. you're gonna have an easier time learning how to become a surgeon and do open heart surgery
honestly, before I try it I'll have to remember how to spell it ;-;
good thing you have your IDE configured so that you get intellisense and autocomplete, right?
ah yes apparently intellisense is case sensitive and always puts the Unity.Math ones first 
i mean, why wouldn't the IDE assume you are trying to use Mathematics.quaternion if you start typing with a lowercase letter? That's literally the more accurate suggestion based on what was typed
oh yeah for sure its just something to be aware I guess, but they both work interchangeably anyway right
they do cast to and from each other, but the methods work differently
for example quaternion.Euler expects radians, but Quaternion.Euler expects degrees
I was working through and rewriting all those methods but put on hold trying to work out how to calculate root values of numbers
ohh shit..radians..my old mistress
Math / Mathf class?
aka "do this complex ass math for me "
Yeah, wanted to make a giant unified one that also included engineering and physics calculations as well as the entire Math and Mathf methods
The engineering aspect made me laugh.. there were 3 different methods that boil down to a = b / c
all I know was the spline class made it akward working with cause its all Unity.Math shit
I guess it makes sense in a way since splines do have lots of math forumals
I decided to create a vector4 which included the variable time
had the "pleasure" of working with float3s instead :p
mathematics library is like "vector who?"
I have no issues rewriting their entire maths library to do what I want, just sad they pushed us away from HLSL scripting
wait don't the new shaders still use HLSL ? or am I confusing it with something else
So they are pushing more towards using Script graph, and writing HDRP and URP shaders became more of a hassle as there seems to be less instructions available. Their goto shader guru (great guy, Chris) mainly focuses on shader graph too
Alright so I have a script "ScoreHandler". I attach that script to an object in the heirarchy which is placed in the scene off the edge of the camera. On another object there is a script "LifeHandler" and I write "Public ScoreHandler scoreHandler" in that script which creates the field. I attempt to attach the other object with ScoreHandler script attached and that gives me the mismatch. Still pretty lost to why.
i trying to invoke a ondestroy on a gameobject without a script on it
collider.GetCancellationTokenOnDestroy().Register(() =>
{
Registry.Remove(collider);
});
is this ok?
you're doing this on the object in the scene, and not in the default references section of the script asset, right?
Well, I'm opening a prefab (enemy) and attaching it. Might be why. Not sure.
oh I thought shadergraph was just a high level graph that still made the code behind hlsl.. i dont know enough about shaders
that method does not appear to be one built into unity, so consult the documentation for whatever asset it comes from to see if that is acceptable
We have literally said multiple times that prefabs cannot reference objects in the scene. Your previous question literally said they were both in the scene
remember that whole conversation about how prefabs cannot reference scene objects?
whats "Registry.Remove"
You can access the code, but I want to "From scratch" it
Prefabs cannot reference objects in the scene
Yea I was confused about that
ohhhhh I see..
What's the confusion?
"Is this object a prefab?" Yes -> "This object cannot reference an object in the scene"
its literally a text file in your assets folder, it has no idea about scene components
its a static dictionary in a static class
dont ahve to worry about it
it called to the destroycancelToken live on the behaviour
Hmm, not sure how else to "log kills" then
hey remember how i provided a link that explains how you can pass a reference to an object when it is spawned from a prefab? perhaps give that a read
or look into events
you should rethink using whatever translation service spat that sentence out
i want to avoid attach script on that object
i can reference to it but i do object.Ondestroy() from outisde ?
ehhh i think this will do
can you not just have whatever destroys the object remove it from the static dictionary?
When editing Prefab assets you can only reference things that exist in the context/“scope” of that prefab asset. Instances of this prefab can reference other things in scene or do stuff via code.
Imagine you are creating a microwave that will be sold at stores. The power cord can reference the body of the microwave but you obviously can’t know what the power cord is going to be plugged into, but when someone buys your microwave and plugs it into their kitchen wall they obviously can connect the two
should have post full context i suppose, im trying to make clickable object
public static class ObjectClickRegistry
{
public static Dictionary<Collider2D, Action> Registry { get; private set; } = new();
public static void Register(Collider2D collider, Action action)
{
Registry[collider] = action;
collider.GetCancellationTokenOnDestroy().Register(() =>
{
Registry.Remove(collider);
});
}
public static void Unregister(Collider2D collider)
{
Registry.Remove(collider);
}
}
if the object is clickable why doesnt it just have a component on it?
yea a collider
myb I mean like your own component
What’s in charge of providing that action?
seems like 1 script would avoid having to do the entire song and dance around
So basically if I dragged that prefab into the scene its instance would allow it, but not any prefab that isn't instantiated yet
yes because its an Instance / gameobject not just a blueprint (prefab)
reread this series of messages: #💻┃code-beginner message
If you dragged the prefab into the scene, you would be able to set the variable on that scene object. The prefab would still not have the value set
Yea I got it it was confusing to me at first
if you try to apply scene references on scene instance to the original prefab it wont let you
If you think of prefabs as kinda boxed appliances like my example comparison the usage of them should start to click when using them
gotcha thanks
Btw nitpicking but no null checking here so there’s some nre potential
A prefab can have other assets in it just fine, Sounds, Other Prefabs, Sprites etc
alr but this is fine right ?
Not saying yes or no to that, nav’s questions/thoughts seem solid, just wanted to point that out
i just trying to seperate out the logic
but ijust realize that this can be hard to debug later, with these action
the logic from what? what problem do you want to solve where is necessary to not keep it simple with a Method / Event called in OnDestroy of the object you want
i was thinking if i have to make everry object a clickable object, the logic now tied to that script and not the one relate. kinda thing
I mean you can still approach it where it just acts as child invoker then parent / manager does whatever
also it was never answered?
#💻┃code-beginner message
the thing that destroys it already has that reference why doesn't it just tell "Hey Manager I Destroyed this, remove it from Collection"
rn if the obj is destroy, the dictionary still hold something there like a null or smt idk right? it will keep growing non stop
but im scraping this out rn cause i want to debug easier
correct Destroying an object in any collection does not remove it
yea so i intent to remove on destroy
yes we understand that part, what seems unclear is why you cannot tell whats destroying to tell the manager of them to remove it from collection
like
Destroy(clickableThing.gameObject)
OnClickableDestroy?.Invoke(clickablething)```
// on manager
```cs
void OnClickableDestroyed(Clickable clickable)
myDict.Remove(clickable)```
what if the destroy not through that Destroy()? like changing scene, go back and forth kinda thing
like which way though, Destroy always gets called between scene changes
(unless its DDOL ofc)
yea but rn have to called
Destroy(...) right ?
put it on the script on the object ?
for scene changes Destroy unless you do it in like a scene switch method
we really don't have the full context for what all you are doing here so it's impossible to give the best suggestion. like why is this dictionary static in the first place
^ also true.. goes back to the question, what are you trying to solve here exactly.. whats the end goal here
click object
that is not an answer to the question
thats pretty vague though..
that part we know, its gonna be a clickable object..
whats the setup, what is it for (i swear if you say clicable ima throw a brick at you), whats destroying it, we don't know these things as we are not in your head or git collab lol
idk how to explain but it does quite a few
maybe can be very long and just go through the entire project fr
i scraping this out rn tho. so i think we can rest rn
hey, is the use of this safe?
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)]
it just makes the function work when scene loads
but it kinda looks scary lol
You cannot solve a problem which yourself cannot explain so you need to rethink the setup probably
alr bet
what is scary lol
if you just want it to run before the scene loads you don't need to use the SubsystemRegistration you can use BeforeSceneLoad. SubsystemRegistration might be too early for whatever it is you are doing
ah just reseting some variables
yeah thanks
after scene load is fine too
give this a read to see when you might want your method to run
https://docs.unity3d.com/6000.2/Documentation/ScriptReference/RuntimeInitializeLoadType.html
basically from bottom to top is the order they happen in
thanks
is there any way to do it after Start?
at that point why not just call a method from Start?
it is static so if it will do it more than once it wont work
call the method from one object in Start?
i think im just complicating things
Also worth noting some specifics about this aren’t documented (iirc if you load scenes in a function using this attribute functions using that attribute will also be fired for that additional scene)
wait a second, i need to remake this whole thing, its not worth it
why do you need to reset variables after Start anyway? shouldn't whatever objects using those variables be able to initialize them theirself?
this is almost always the case 😆
im trying to optimise some scripts
but i dont want to make it with a helper script
that's incredibly vague
so that the gameobjects wont need to search one another for the player
so that only one script from all of the scripts will be chosen to search, and then will give to each
sounds like you want an event instead
and the others will just wait until they are given
