#π»βcode-beginner
1 messages Β· Page 763 of 1
Yea thats what I meant with possibly doing something more than once per frame
Well idlebehaviour has a public var for attackscript just fill it out in the inspector for now
it wont let me drag it in from project window so should i try put it in the game or something?
You need the attackscript to bea component of an object yes
then drag the object into that section?
just add it as an Empty gameobject
if its in the scene you don't need a direct reference.. b/c its a static singleton instance..
you can call it from anywhere
yeah i just tried this and it for some reason isnt working
Okay so...
Make an empty GameObject in the scene,
Call it "Singletons" or "Shared" - something that makes it clear, this is "one instance" stuff (static)
And add as a component, the Attack_Script (aka CombatManager)
Now you see how you have public Attack_Script instance ...
In the video he has... public static CombatManager instance
The static keyword there means, the instance exists for the entire time your project is running
So you could access it, like... Attack_Script.instance
ahh shit, yeah what @rocky canyon said π
Does he even have to have an instance of the component in the scene to access the static .instance? π€
does anything change that its on IDLE in the animator and not a gameobject?
yea thats what i was saying to do ^ lol
as long as its in ur hiearchy it doesnt really matter where
if u disable the gameobject or something u no longer have access to it..
i see. but if the class itself was static too, then the static members would exist without any component instance in-scene
was it not a monobehaviour?
can't have a static monobehaviour right π€
ohh no its a StateMachineBehaviour.. yup i have no idea about those..
im tapping out π
ya i didn't notice htat
since its a statemachinebehaviour do i not do the video thing you sent?
im not sure.. thats y i removed it
ngl im tapping out too. this is too overcomplicated, for a basic "2D character sword combo" π€·ββοΈ
yeah i have no clue what im doing ive been doing unity for 2 months from nothing
the statemachinebehaviour thing i've never used. soo i dont wanna give misleading information
i've been learning 4 years and i've still not used that before
yeah i think it like, directly interacts with the Animator State
lol Β―_(γ)_/Β―
shit that could be kinda useful .... hold on...
should i just scrap the video and try find something new then?
if ur only 2 weeks in i'd def hold off on the statemachine and behaviour tree stuff
start out with simple animator stuff.. basic enum state machines.. and directly controlling the animator w/ booleans and triggers
yea, when i see this thing i run away with my tail between my legs
yeah im just trying new things for my college course
ya, i get that.. but even in college you want to build up to the more advanced things
@rocky canyon wait this is kinda cool
Apparently it gives you callbacks for when Animator enters a state, exits a state, etc π€
ya, thats all you my friend π
alr ill try find another video thanks for your help and im sorry i sort of wasted your time
nah u didn't
thats why we're here π§‘
as a beginner i just did ur basic animator setup
- use transitions to control when and how u transition and to what state
- use animator parameters to control that stuff.. (booleans, triggers, etc)
then its just animatorReference.SetBool(Run, true);
but as you get more advanced you can def look back into behaviour trees and whatnot
ya, i learned about it not too long after learning about statemachines...
but with a statemachine you can control callbacks and whatnot via ur code-base
animator just gives u an opportunity to lessen ur work-load i guess
if ur down to learn
https://gameprogrammingpatterns.com/state.html
give this a read, if you wanna make something like Dead Cells i recommend you get a state machine going first
The basic idea is,
All states have their own version of these basic couple of functions
OnEnterState, OnExitState, DoSomethingEveryFrame, CheckIfNeedToChangeStates
i recommend you get a state machine going first
π― you can take what u learn by building ur own statemachine and apply it to other things
And with that, you can ... literally do anything. jump, swim, fly, attack, combo, combo cancel, etc
@flint rover
https://youtu.be/Als_d-UIgVo
Here's a slightly less outdated video with more details.
He builds an enum-style state machine (not inheritance / hierarchical) but it shows the idea which is the gold here
Here's how to use a State Machine in your Unity game. This is an excellent mechanism for keeping your code streamlined. NEXT VIDEO: https://www.youtube.com/watch?v=5s_gcWef4pY&list=PLydLF_SVNKYaY5YnH7amiEeiUAVWRBCu3&index=12
By using a state machine you can effectively control when your player in a walking state, versus a jumping state, versus ...
ok yeah great im just giving that document a read then ill watch this video and try that thank you
Yes make sure to use an Enum - the video uses strings i think which is not as efficient
One of the first goals with state machines is to reliably track and manage basic movement states - idle, jog, jump
I would recommend to track it in OnGUI - try to avoid Debug.Log when possible, as it lags out the Editor.
// after setting up some Enum
private MyStatesEnum playerCurrentState;
void OnGUI()
{
GUI.Label(new Rect(10, 10, 160, 20), "State: " + playerCurrentState);
}
ya, thats what i was mentioning earlier.. start with basic state machine (enum) and work ur way up
Once you get idle, jog, jump working solid, then you can start to add stuff like,
"if player is in idle state, and attack button pressed, switch to AttackCombo1 state"
"if player is in AttackCombo1 state, and the attack button is held down, continue into AttackCombo2 state"
etc you see the idea how they chain together
the Enum way is a little hacky but, keep in mind the 4 main State Machine functions (verbose plain English used for clarity)
OnStateEnter, OnStateExit, DoThisEveryFrame, CheckIfNeedToSwitchState
@keen dew hey, i followed another approach, created a empty object children of player and set it's position to the center of the screen by code, so i just changed the ray origin to that object π works fine with just 1 ray
it's like having a small floating robot near your with a ray hehehe
Hi there, I'm running into a problem where I have a skinned mesh renderer that's tposing in builds but works in editor. I've already tried marking the FBX as read/write enabled. Any ideas?
#πβanimation π ask here
I solved it actually! I had to make sure that the model was placed somewhere so Unity would include it in the build.
How was the model winding up in your game in the first place, then?
It's true that assets that aren't referenced in any scenes and that aren't in a Resources folder will not be included in the built game
Yea something else must have been wrong like not playing any animations on it
I was swapping out the shared mesh of a skinned mesh renderer
Can I get some advice? How do you start working on a modular system you have no idea how to make? For example, I KNOW what I want it to do. I want standalone "zones" for each level or area, that have their own game logic flow. Like triggers, interactables that subscribe to the manager to dictate what happens, but logics wise, I have no idea how to do it
Please ping me if anyone replies
Don't think that works unless they have the same bone structure + bone names
Even to me this is too vague. Got any concrete examples of what you want to be modular?
duplicate the skinned mesh renderer portions and swap out the shared mesh and shared material and presto, skinned mesh animation with swappable parts
start by coming up with a fully concrete description of what you want to do
Then they may all need to share the same avatar to share bones, i forget
you can't instantiate a skinned mesh renderer because the bone data isn't copied
so then you spawn a prefab
to be clear my stuff does actually work, it was a "unity didn't package the mesh" problem which I solved
like, an asset inclusion build-time error
No I don't, but let me be more descriptive. Let's say I have made a trigger, where on trigger enter, it checks if it's active, or if the bool m_OnEnter is checked, then it checks for the player tag. Then it sets off an event handler. I want a system where you can set that trigger as a variable, then do
m_Trigger.OnEnter += SomeFunction;
Now, I know how to do that, but in terms of initializing the zone I'm in, I have no idea
So you want a component to handle that work?
Let's say each area is a zone, and when you enter, it initializes all of the data for that zone. Triggers, doors, etc and what to do when they are interacted with
yes
Like I already have the logic all in my head for how that all works, but I just don't know how to write it
So how about this:
PlayerTriggerEnter -> has event for when the player enters a trigger
AreaManagerBase -> base class that calls some virtual Init() func using PlayerTriggerEnter
Then you inherit from AreaManagerBase for each area class you create
But in terms how HOW that is initialized? Like do I need just some trigger that covers the entire zone, and make IDs for all the zones, and then go through all the IDs, and if that zone has that ID, initialize the zone with that ID?
That seems almost too easy
Why do you need to perform setup work when a player steps inside some area?
Is this even needed?
Well that's the way they did it in Bendy and the Dark Revival
A zone is a section of a game. It can be rooms, levels, etc
If the player steps inside a room and you want a cutscene to begin and spawn a boss, id also use a trigger with some component that calls an event (and ensures it can only be called one time)
Yes
If I had to guess, I guess the manager is there to make sure that the game knows if you've already been there or not, and so if you load it, the game doesn't say "hey, they haven't been here before, deactivate everything"
Apologies, I'm bad at conveying thoughts
Well we dont always have to explicitly disable things but it can be helpful sometimes
valve did this a lot in HL2, in route canal the guy you meet where you fight man hacks gets killed once you get far away enough
They have specific entities and an input/output system so it was easy to add such logic in map
We can do the same with UnityEvents
or you use custom components and Interfaces to invoke things on trigger enter
Yeah I know how to invoke things. My game was gonna feature an async save/load system so I just wanted a manager so that when I load the game save, it goes "Ohhhhh the player is on this zone" and makes sure to only initialize that portion, then when they enter another zone trigger, the next zone initializes all it's data
That sounds like you want some kind of zoned loading system where things are split amongst many scenes/prefabs
Then it does make sense to have data to link these together and to know what to load in later
Oh so it is scene based, not just area based? I was assuming with how big the studio is in Bendy and the Dark Revival, every few rooms or two was one big zone
Wait yeah nvm it is area based because they made one scene for the entire studio
Hello,
I have a problem with my targeting system, where I have problems with my enemy deaths.
It just adds/removes an enemy to the kill list when something with a "canBeAttacked" tag enter it's range
private void OnTriggerEnter(Collider other)
{
if (other.CompareTag("CanBeAttacked") && !enemiesInRange.Contains(other))
{
enemiesInRange.Add(other);
}
}
private void OnTriggerExit(Collider other)
{
if (other == null) return;
print("Something exited");
if (other.CompareTag("CanBeAttacked") && enemiesInRange.Contains(other))
{
enemiesInRange.Remove(other);
}
}
protected List<Collider> enemiesInRange = new List<Collider>();
Enemies in range represents the lists of all the enemies in the tower range, precisely, all the collider I detected when one of them entered of left my tower's range.
void Attack()
{
if (attackCooldown <= 0f && enemiesInRange.Count > 0)
{
foreach (Collider col in enemiesInRange)
{
if (col == null) break; // Works well until you have more than one enemy
Enemy enemy = col.GetComponent<Enemy>();
enemy.damage(damage);
attackCooldown = attackspeed;
print("I attacked " + col.gameObject.name + ". Life left : " + enemy.getRemainingHealth());
break;
}
}
}
I use this simple "attack" function that does try in the Update, to shoot the first enemy in it's enemy list until it theoretically triggers the OnLeaveTrigger.
public SphereCollider rangeCollider;
public void damage(float dmg)
{
this.health -= dmg;
death();
}
public void death()
{
print("Man I'm dead");
Destroy(gameObject);
}
However, enemies needs to die and I don't think the destroy() really triggers the OnLeave
Did you forget that we can load many scenes at once?
Oh shit yeah
if you want light baking to not be annoying a f then you would put things in seperate scenes
Okay so for example then, there's a room where Audrey goes in, walks under a vent, and the vent smashes open with a dead ink creature hanging down, then a PA comes on. That could be a zone I guess
You would split things up in a way that makes sense (e.g separated by doors or corridors)
Ofc the old way was just to have a loading screen to unload and load the new areas but there was always some "transition" point/area
Again, in HL2 it was selected carefully and meant each map needed to duplicate the transition area
Either:
- have enemies keep track of which zones they're in and notify those zones when they die so they can be removed from the list
- Have enemies fire an event when they die, and when they enter one of these zones add an event subscriber that removes them from the list when they die
@umbral hound I keep mentioning HL2 because amazing game but even with its age it ~~was ~~IS an very important game and thankfully mapping concepts are well documented: https://developer.valvesoftware.com/wiki/Level_Transitions
i need help on how to assign field in this context
A tool for sharing your source code with the world!
its a pathing assist, to point where npcs should go to move to another area
perfect timing lol, its a level transition but mine is light 2D game so I just teleport them
Can you explain what field you're trying to assign exactly?
And what trouble you're having with doing so?
i cant access the road, i leave comment on the code
I only see one field in this code:
public Area[] areas;//location with road details
sec
you mean this?
for (int j = 0; j < area.roads.Count; j++) //ERROR: Use of possibly unassigned field roads
yea , how do i assign it properly with some default value ?
I mean would a default value help you here?
It would be null and you'd get a NRE
how about:
Area area;
area.roads = null;
bool found = false;
for (int i = 0; i < areas.Length; i++)
{
if (areas[i].locationName == initialLocation)
{
area = areas[i];
found = true;
break;
}
}
if (!found) {
initialRoad = default;
destinationRoad = default;
return false;
}
//find the correct road element
Road road;
for (int j = 0; j < area.roads.Count; j++) //ERROR: Use of possibly unassigned field roads```
this is made a little more verbose/complex by the use of structs instead of classes, btw.
If anyone knows alot about fears to fathom type games, I appreciate if you write me π
if Area was a class you could:
Area area = null;
for (int i = 0; i < areas.Length; i++)
{
if (areas[i].locationName == initialLocation)
{
area = areas[i];
break;
}
}
if (area == null) {
initialRoad = default;
destinationRoad = default;
return false;
}
//find the correct road element
Road road;
for (int j = 0; j < area.roads.Count; j++) //ERROR: Use of possibly unassigned field roads
i tried making Road [] roads and set area.roads roads. i can go with this.
i will assign value to roads later
what i mean is i could make another areas2 array initialized with default values, then load them with areas data from inspector. but is it possible to do it as it is with additional code ?
because how many location and road will be there is known
ill try with dictionary, i made something similar while learning dijkstra. but it'll be nice to know how to do it with struct thus i proceed with it
Hi could someone possibly help me please. Im trying to make these two vr potions the when mixed together (causing the shader to change colour into a mix of the two) and poured onto a gameobject cuases the game object to change texture. this is the code i have for tyhe flask and the texture one for the object however when tryoing to mix the potions the liquid just disapears
What kind of object is it?
How is the shader/material set up?
You seem to have two different lines of code in two different scripts changing the material to two different things?
Also:
- Have you verified the code actually runs?
- Are there any errors in the console?
@siennashroom muted
Reason: Sending too many attachments.
Duration: 29 minutes and 56 seconds
Another reason to use !code instead of a ton of screenshots
π 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.
how many is too many ? just in case..
for (int i = 0; i < areas.Length; i++)
{
if (areas[i].locationName == initialLocation)
{
if (areas[i].roads != null)
{
for (int j = 0; j < areas[i].roads.Length; j++)
{
if (areas[i].roads[j].endLocation == destination)
{
initialCheck = true;
initialRoad = areas[i].roads[j].startPosition[UnityEngine.Random.Range(0, areas[i].roads[j].startPosition.Length)];
destinationRoad = areas[i].roads[j].endPosition[UnityEngine.Random.Range(0, areas[i].roads[j].endPosition.Length)]; break;
}
}
}
else Debug.Log("this area has no roads"); break;
}
if (initialCheck) break;
}
return initialCheck;
i made it !
GUYSSSS can explain? there are too many script types, whats the use of each of them? π
That's only 4 types
you only need to worry about MonoBehaviour if you're just getting started
Playables are for https://docs.unity3d.com/6000.2/Documentation/Manual/Playables.html
MonoBehaviour is a regular component script
ScriptableObject is for making custom editor asset types
that's all
God has a special place for you on heaven β€οΈ
Found out you can add more, not sure how much unity (the company not the game engine) likes that though nor do i know how to add other classes as a default in new projects.
I dont think they care
anyway to make raycast hit even the inside of collider ?
Queries Hit Backfaces
ohh.. well sounds like you might need to create some primitive's in blender or something
! 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.
so is there any way to avoid gimbal lock when using addTorque and 2 axis? Seems impossible
Any code to checkout?
just adding AddTorque to X and Y based on mouse axis, nothing more
I am asking for the code to find out, if your gimbal lock is coming from addtorque or your calculation what torque you set
It's made in playmaker for prototyping
It just gets a mouse x and mouse y value and places them in a vector, that's all
Does it just call AddTorque with a correct axis and rotation under the hood?
yes
the problem is if I move my mouse diagonally up and to the side, the player drifts more and more on the Z
do you maybe need to be using AddRelativeTorque? (vague guess not sure)
this is that. That little check that says "self" means it's relative
So its calling addrelativetorque? or addtorque with some calculation
You can't do it without complicated calculations to figure out the "real" torque
that's a legit question actually, but does it make a difference in reality? Won't the same thing happen regardless? I mean I can check but....
also, my rigidbody is frozen in Z but that doesn't seem to help
The issue is that when the character is tilted on one axis, you actually don't want it to rotate on the other axis but that rotation should be adjusted as well
seems to me like I will need to correct Z rotation each frame after applying torque to x and y
ah, its frozen in Z? that can lead to gimbal lock. as Nitku says, its like hard setting only two axis and therefore overriding the correct quaternion calculation for the resulting orientation
you mean to tell me it wouldn't happen if it weren't frozen? But I'm pretty sure it acts the same. I can check real quick
I didn't understand this
nope, I'm still to the side when unchecking freeze rotation
Did you understand this
So what exactly is happening when you rotate over the 360 degrees? Is it flipping back
I understand the gist of that message but I don't understand how lol
imma just snap a video real quick
If you add both X and Y rotation to a character it'll always also rotate on the Z
so you can't just "naively" do X and Y rotation and expect that Z will not change
yea ok fair, but what is the solution?
It's not quite the same but it's somewhat similiar if you move a character horizontally and vertically at the same time, it will move diagonally even though either of the two movements are not diagonal by themselves
Don't use torque to rotate the character
If you really want to use torque, I'm sure there are articles on the internet how to do it. But there's no simple solution that you could just apply to fix it
but part of the reason I switched to a rigidbody is to get natural rotational collision π’
I didn't have these problems with the character controller
bullshit, internet is useless and gpt is just lying as always
if internet is useless you are not good at interacting with it
Usually characters rotate using torque only on the Y. Rotating up and down is done with the camera so that the player doesn't bonk on things when looking up and down
that's fair but my character is a diver and needs to move and rotate in 3d
possible
I found one alleged solution but it's in js and I'm too stupid
i love using unity
!ide
If your IDE is not autocompleting code or underlining errors, please configure it.
Select one:
β’
Visual Studio (Installed via Unity Hub)
β’
Visual Studio (Installed manually)
β’
VS Code
β’
JetBrains Rider
β’ :question: Other/None
not much we can do with just errors, let alone errors with only half the message
i dont think its that
um ok let me send the full error
Assets\Scripts\ThiefAI.cs(8,13): error CS1069: The type name 'NavMeshAgent' could not be found in the namespace 'UnityEngine.AI'. This type has been forwarded to assembly 'UnityEngine.AIModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' Enable the built in package 'AI' in the Package Manager window to fix this error.
idk what happened
i restarted unity editor and now i have this error
did you update unity?
Assets\Scripts\PhysicsItem.cs(11,13): error CS1069: The type name 'Rigidbody' could not be found in the namespace 'UnityEngine'. This type has been forwarded to assembly 'UnityEngine.PhysicsModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' Enable the built in package 'Physics' in the Package Manager window to fix this error.
no
i did absoulutly nothing
i just reopened unity
Is it only those four errors?
yeah
and they wernt there before
i reopened unity i got a message saying i have compiler errors
What does your IDE say when you open those scripts?
let me chack
nothing
according to ide there are no errors
what happens, when you try to update those lines, just rewrite them with a space or something and save them?
let me try
nothing
still the same error
when i was opening unity i got a message saying UNKNOWN HARD ERROR but i ignored it
Good point ignoring cap errors π Did you backup your project?
no
(I created the project yesterday)
Ah, id back it up and delete the library folder and see what Unity does
imma reopen unity
but i gotta go somewhere
so when i come back i will reopen and see
what will happen
Good luck to you
thanks you too
Hello, I can't submit my project in Step 6 on this page:
https://learn.unity.com/pathway/junior-programmer/unit/manage-scene-flow-and-data/tutorial/submission-data-persistence-in-a-new-repo?version=6.0
Tried uploading a picture or a video, but the api returns a 400 Bad Request everytime:
{errorCode: "InvalidParameter", message: "The given parameter is missing or invalid", target: "stepId"}
I can't continue the Pathway, any solution?
Edit: Asked in General as it's not really code related...
Free tutorials, courses, and guided pathways for mastering real-time 3D development skills to make video games, VR, AR, and more.
How is this a code question?
Yes sorry, I edited to mention I also asked in General, I was following the programmer Pathway that's why I came here by reflex, sorry
is c# the best language ever
matter of preference
there isn't a "best language ever", really
but c# is pretty neat tho
it is yeah, definitely one of my favourites
I love c# much better than whatever java's got going on (omly other language i know)
i've (casually) used c#, java, python, lua, php (html, css and sql i guess), gdscript and a tiny bit of c++ and i vastly prefer c#
i like python more than assembly, i like luau more than python, and i like c# more than luau
has its flaws, but it is pretty good
that's a pretty common feature i imagine, no?
python and luau do it with if statements which is ugly
oh yeah awful
also the type system in luau doesnt really like it
it usually comes with strict typing, which is not a guarantee
i like that in c# types are like a part of the language, in luau it feels like the code and types are 2 seperate things, and types are just to help you remember what you called your methods
c/c++/c#/java have overloading, js/ts/python/lua/bash don't, for example
makes sense, yeah
Yeah i guess i've also used python and lua but simple stuff unlike c#
Hello. Is there some default way to handle jumping colliders in 3d? as dumb as this sounds but we didn't think about it but obv when you jump your character gets a tad smaller and the visual would technically allow you to move forward but it is blocked due to the collider being full size
you could just make the collider smaller
I did some porting from c# to ts/js ages ago and i had to do shit like Blah(), Blah_1(), Blah_2() cus no overloads π
Sometimes I am dumb indeed
i need help about physics or idk why but same jumping code i used earlier doesnt work now mass and default gravity project settings are normal:
if (Input.GetKeyDown(KeyCode.Space) && isGrounded)
{
rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
}
are you getting errors
do you have other forces acting on the rb? is the velocity being set? is the transform being modified?
rb.linearVelocity = yeniHiz;
only this yeniHiz is a vector3 btw that manages w a s d controls
π 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.
if (Input.GetKey(KeyCode.W))
{
yeniHiz += transform.forward * hiz;
}
like this
S is -transform.forward *hiz; and it keeps going like that with -transform.right transform.right
ok restarting my laptop worked and my heart litrally came in my throat because it opened a emty scene named untitled and i though i lost all my progress
but no i had to open sample scene
that's a terrible way to handle that, but also you're overwriting the Y velocity each time you use that vector3 so you're preventing your jumps from happening correctly (also preventing gravity from working)
will it fix if i turn it into vector3.fwd vector3.right vector3.left vector3.back
its the same thing...
what is yenihiz and hiz
yenihiz is a vector3 0,0,0 hiz is speed
ok i think you should use rb.addforce or maybe rb.moveposition instead of transform its super terrible
No these vectors still give a value of 0 for y which would still override the gravity and jump code
i used transfrom.translate once and my stupid controller turned into a plane with bad collision detection yeah so dont use it
π
they aren't using transform to move here. it's fine here
you need to apply the existing y velocity
they are using transform.forward which can mess things up a little
that just provides a direcetion
there is nothing inherently wrong with that
It will be slightly incorrect if the rigidbody has interpolation enabled, since the transform will be lagging behind the actual position of the rigidbody
no it is not enabled
how do i do it
add rb.linearVelocity.y to the velocity vector that you're applying
unity defualt gravity is stupid you should add a downward force whenever isgrounded is false
if you're referring to a stronger down gravity, that's a separate thing.
please stop recommending random irrelevant things.
but it should fix the gliding right?
e.g.
rb.linearVelocity = horizontalVelocity + Vector3.up * rb.linearVelocity.y;
assuming that horizontalVelocity has a Y component of zero, of course
no, that's happening because the rigidbody's Y velocity is constantly getting set to zero
Unity's default gravity matches real-world gravity. This will seem wrong if...
- ...you're used to, say, Roblox's default gravity (which is extremely strong)
- ...your objects are very large
oh ok me is dumb
If horizontalVelocity might have a non-zero Y component, you can discard it pretty easily
Vector3 projected = Vector3.ProjectOnPlane(horizontalVelocity, Vector3.up);
This method discards the part of the vector that matches the second vector
Very useful for turning a tilted direction into a flat one
(e.g. if you move relative to the camera, and the camera is looking at a downward angle)
okay tysm it fixed, idk why but i think it stopped working against the addforce and it became equal to Y force aka jump
AddForce tells the rigidbody that it's being pushed, and it will react during the next physics update
However, you then immediately told it that its Y velocity should be zero
i get it thanks
guys how does transform.setparent work
like, the internals? or what it actually does?
for the latter, well.. it just sets the parent
can i use it to parent any object with any object?
like it doesnt matter where the code is
unless it's circular, i guess
why would it matter
if it's executed on the main thread, it'll do what it says it'll do
that's.. how code works
i'm not sure what you mean by "where the code is"
i wasnt lying when i said i am dumb but i figured it out
what were you thinking about? there might be something deeper you're unclear about that i could help with
i am just trying to make a thief ai which basically steals item but i cant figure out a good way to make it
steal stuff like a thief
You can start with state machine and nav mesh to see how a classic AI is made in Unity
A thief would likely have a grabbing mechanic and an inventory system
i have the ai set up
i just need to make the stealing part
yeah no i am not making a inventory systemπ π
Hows it a theif then...
And what does any of this have to do with the original question of SetParent
there would be multiple thiefs each thief will only grab one item and run away with it
to make the thief grab stuff
It's just a suggestion. Yeah, one item would not need an inventory
Just simple grab and hold
yeah its a roguelike game where you are defending your house from like a million thiefs
and you lose once the thiefs have stole items worth over 100,000$
I'm looking a tutorial which makes a custom pass volume, but i only see global, box, sphere and convex mesh volume. Was it removed or is it just a package which im lacking?
those sound like two different things entirely
can you show us what you're looking at?
well... in this video you'll learn how to make a dope damage screen effect in Unity.
subscribe for a cookie :)
shader and code https://github.com/Mohammad9760/Unity_Special_Effects
I'll show you how to create a full-screen shader for a damage screen effect using shader graph that works both in HDRP and URP.
Support me on Patreon β https://ww...
and where are you seeing "global, box, sphere", etc. ?
oh, I see
can you add a Custom Pass Volume component to an existing object? the menu item may have moved
I believe Custom Pass Volumes are HDRP-specific. I only see this in a URP project.
which would explain the issue
You should absolutely be able to do this effect in the URP. I'd ask about it in #1390346776804069396
I just don't know the exact feature you need
I'm guessing it would be a custom render pass https://docs.unity3d.com/Packages/com.unity.render-pipelines.universal@14.0/manual/renderer-features/custom-rendering-pass-workflow-in-urp.html
(the name alone sounds promising :p )
I think you just can't use the Volume system to control when a custom pass applies
I vaguely remember figuring this out for a game jam a few years ago
alright. Thanks for the help
This isnt really code but could someone tell me how to fix this like Ive tried doing the empty gameobject thing but I js dont get it
supposed to be the other way if u couldnt tell
I'm working on a video game and I wanna transfer all my assets from one version to the other from a separate computer. I keep getting errors on the part where I need the character to move and handle its script when I transfer to the new version.
So I tried moving my assets to the old version and keeping the scripts the same, but it still causes me errors.
I want to know how I can transfer all the assets I've changed in my new version to my old version without ruining my scripts. Any thoughts?
Note: the new version has the patterned flooring and lighting. The old is the grey floor with the model in the middle that has all its scripts and commands set so it can move with my Xbox controller.
"Fix this" tells us nothing whats wrong with it?
Do you have code that affects its rotation?
its literally bc of this
but how can I fix this
the green arrow is pointing down
when I need it to point up
ik its bc of how the model was made and that
ive tried doing an empty game object but that hasnt really worked
create an empty object and parent the existing object to it
you can now freely rotate the child
spin it around so that it aligns with the parent's axes
ive tried that but like due to the way my pickup script works it js doesnt let the player pick it up
im trying smth else rn tho
sometimes to achieve the desired results, you have to move some things around 
then it's time to modify the system π
you can put a collider on the parent object, yeah
Hello i am seeking help with programing problem. The problem is about saving system in unity the player will save some postion in JSON file but when i go back to main menu and back to the game the player will spawn some were else than i saved
Could you share the code
to dms or here
π 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.
https://paste.mod.gg/zfamlvcsepgo/0 here if i have it good
A tool for sharing your source code with the world!
Missing the actual parts where the player data is saved/loaded here
also an explanation of which components are in which scene(s)
and are you using additive scene loading?
i will send the whole code system this was just SaveManager
A tool for sharing your source code with the world!
What about:
DataHandler
PlayerMovement?
actually this is the same file you sent above
Oh I see they're all in the link
Is the link ok?
Can you answer about the scenes?
Are you transitioning between scenes here? Are you using additive scene loading?
Not using Aditive and yes
Help. If the ball moves to fast, the boolean vector3.distance wont be true.
https://paste.mod.gg/tkskwpocihlp/0
A tool for sharing your source code with the world!
DataManager doesn't seem to be DDOL, even though you are storing a static Instance property for it.
So most likely DataManager is simply being destroyed when your scene is loaded
and then a new one is loading but all the new one does in OnEnable is subscribe to sceneLoaded
it won't actually run the code for loading the scene
shouldve minimized the obs software but i hope its still good view
You can verify this with some basic logs
i have all of the manager in one core scene that dont uloands and the object that have the datamanager have parenting object with dont destory on load
anyone know a good website to make UML class diagrams?
draw.io supports this
i have all of the manager in one core scene that dont uloands
You said you weren't using additive loading though?
Ok so the parent is DDOL
What debugging have you done for this?
I was loging the player position where he wa standing and position what i saved to confirm that both of those position are same
the were same so i tried to log the position that he loads and this position was diffrent
Is there a channel where I can ask about why my light cookies are not working in unity?
Sorted, was disabled in URP settings
hey guys i got a question, i want to get into programming unity but idk where to start
im trying to make something simple like a rhythm game
unity provides a bunch of tutorials at !learn
was that the wrong shortcut
close enough
ahh alr thank u so much
I'd get comfortable creating basic interactions first (so, making a little platformer game will help a lot)
The main thing you need to do in a rhythm game is display notes and then decide if the player's input lined up with a note
There are a few gotchas here (e.g. what if the game freezes for a bit? the music might get out of sync)
yeah thank u i had been searching for a tutorial for something like this but most of them are pretty old and look pretty bad too
i still need help with that
You might need something like "coyote time" here
Coyote Time is a trick where the player is allowed to jump for a moment after falling off a platform
(modeled after our beloved Wile E. Coyote, who can float midair until he notices he should be falling)
Instead of having a boolean called canGrabBallLeft, I'd create a field called lastLeftGrabTime
If you decide the player can grab the ball, store Time.time into it
When the player tries to actually perform the grab, check if lastLeftGrabTime + 0.5f > Time.time
this would give you a half-second grace period
(oops, had the condition backwards; fixed)
this is gonna sound so dumb but do u maybe have rhtyhm game tutorial thing i could learn from?
these tutorials dont seem to teach me how do anything remotely close too what i want to do
sorry
I don't know of any (and I haven't made a rhythm game before)
You're going to want to get some general experience first, though
well alr which one should i learn first?
theres like 50+ i see
wait nvm i found it
thank u anyways
Hey, when it comes to scale of 2D or 3D objects, do you guys use absolute size or scale factor?
Any rule of thumb when to use what?
I create all of my models (3D) and sprites (2D) to have the appropriate size at a scale of 1
for example, if a sprite is meant to be 1 meter tall and has a PPU (pixels per unit) value of 64, then the sprite must be 64 pixels tall
similarly, I get the scale right in Blender, rather than tweaking it after importing
I've thought about this when designing variably-sized characters
I can see some value to having everyone be equally large at a scale of 1 and then just growing or shrinking them
(rather than baking those size differences into the armatures and models in Blender)
Especially if there is no obvious "correct size"
So 1 "unit" = 1 meter ? Is that agnostic to what my camera or my viewport or resolution looks like?
I often would like to have metric units, but was not able to figure out what 1 m means in Unity up to know.
That's the convention, yeah
Notably, if you're using 3D physics, that's the default unit scale
Good to know. Ty.
The only place where units have no meaningful world-size is on screen-space UI
where one unit is generally one pixel
(I think 2D physics also expects this, but I'm not sure)
One could assume that the 1 unit of mass for rigidbody would equate to 1 kg aswell then yeah?
This is really important if you are doing pixel art
Yep!
Pixel art can't be freely resized without looking really janky
so you need to nail down a PPU (how many pixels takes up one unit of space in the world) as well as how big your viewport is going to be
(I mean, you can absolutely mix pixel sizes if you want...)
it's not necessarily awful, but it often is, haha
if you have 100 pixels per unit and a 1000 pixel-wide screen, your camera can be exactly 10 meters wide
it can also be 5 meters wide, 3.333333 meters wide, etc.
(the Pixel Perfect camera components figure that out for you)
but this is all irrelevant if you aren't doing pixel art
So not made out of water, but styrofoam, huh? π
a one meter cube that weighs 1kg would be quite low-density, yes :p
Wait lol totally right, a 1m^3 (the volume of the basic block) assuming it's water would be 1000kg
But its only 1kg in unity
Unity physics often feels floaty because you've got the wrong numbers
(well, note that it doesn't model actual air resistance, so mass doesn't really matter)
rigidbodies do have drag, but this drag doesn't grow as fast as air resistance does
you can model it yourself tho
actually you can't really read physics default mass as kilograms, particularly in relation to drag/friction/restitution, this is mentioned in the docs which point towards these values having to be found iteratively/empirically, if you want to use numbers approximating reality for mass, you need to turn on all the (more expensive) phyics settings.
Theres actual physics setting you can change in unity?
What how is it ive used unity for a year and a few months now and not heard of this :/
it wont ever be fully realistic without adding your own (complex) simulations, but it gets you closer
look for "friction type" and "solver type"
Oh i gues i know of the friction (never used it though)
the "Temporal Gauss Seidel" solver is somewhat required if your objects have large mass differences.
after all PhysX is a generic collison solver and query engine, and it makes a lot of compromises to achieve that generality. Unless you truly need the native performance of the N-body collision solver, you can build a custom force simulation yourself, easily, on top of the query API. Generic collisions with restitution and friction always are complicated though.
hi, I have a problem in my game, I've an interacting system with doors and once I run the game/enter playmode, the doors open themselves, https://paste.ofcode.org/psG53awizPxGSqHdFskPWu here's the door script, I call OpenDoor() function when the player interacts with the door
the only problem is they open themselves at the beginning but after it works pretty well
Is the default animator state set correctly? Oh nvm you are telling it to just play an animation by name so you may not understand those yet?
You should be using an animator variable (bool) and state transitions to control the open and close animation playing instead
also why are there loads of random new lines in the code?
Show your animator state machine
why would I not understand this? I'm not a total beginner and yes I'm using triggers it's just an old script I've sent by mistake
btw:
if (!open) {
}
else if (open) {
}```
Can just be:
```cs
if (open) {
}
else {
}```
Well what I saw made me think you were a beginner who didnt know (and this is the code beginner channel)
Yep, still show us your animator state machine
it can be but I'm used to using this style
what does it change? 2 lines less
You shouldnt use triggers but a bool
no it's more logically correct
the else if implies there can be other states besides true or false
and may lead to coding errors like adding other else conditions
it's also less performant (negligibly)
definitely not a lines of code thing
ohhhh
If you use a bool for the open state it will be easier to let the animator transition back correctly to the new state
I thought you meant the style with tghe }{
tbh I wanted to make an else too, one if one else if and one else, its just a basic script
there will be another way to open the door
but how? bool can only be true or false - only two states
Anyway - can you show us the state machine lol
there will be more conditions with &&, man,sorry but I'm sick don't overthink those please lol, else if is probably not the cause of the bug
I'm not going to compare with the bool variable only
@wintry quarry
I always post here and no, but I'm sometimes using Animator.Play(); tho
and what would the bool help with tho? I mean I know it'd be better but there are a lot of people that use Triggers for everything
this probably isn't the cause of the issue
Not to further detract from your root issue but worth mentioning that troubleshooting like that isn't something to take personally. People make games and people are consistently stupid and it's worth systematically identifying potential problems and ruling them out in order to reliably resolve issues
You need a transition from open -> close and also close -> open that uses your bool
You want to setup exit time on the transitions to work as you desire (to either wait till the end of the animation or be allowed to transition at any time)
Now this introduces a new issue btw. If your animations are to open and close the door, you need a third animation that is either empty or static for the default state of the door
This should be the default state. This will prevent the door from playing an opening or closing anim when the game starts
....what do people have today wtf, man I'm just answering the way I answer
I've has exit time to 1 rn and okay I'm going to use a bool variable instead
I got no beef with you homie im just saying no one else has an issue either, asking basic questions is just a good way to solve problems. Animation stuff like this is a pain in the ass so i totally get your frustration
and for the default state, making an empty state wouldn't work?
fr
It will work fine. If the default state is closed then as long as you have a transition from default -> open then the door can open and close.
Hopefully this is making sense
yess, I'm doing it rn, I hope it'll work
ty
@grand snow I've just changed it to work with a bool "open" variable, and it does the exact same thing as before
I think the entry state opens the doors, I don't know though
select the object after it animates and see what the current animator state is
(in play mode)
I presume the default state or transitions are incorrect
it's the new state empty state
If how the door is at the start is closed, you only need a transition to "open" that uses the bool "open"
what.???
the doors open themselves at the beginning without me interacting with them
I have a script that has a bool variable called open, I set it to false in Start() method, then in the Update() I've an if and an else condition, if (!open)
{
animator.SetBool(boolName, true);
open = true;
src.PlayOneShot(openSound);
}
else
{
animator.SetBool(boolName, false);
open = false;
src.PlayOneShot(closeSound);
}
- animator transitions have no conditions set
- something tells the door to open on game start
- empty state has an animation assigned
Im thinking one of these
it's flipping back and forth every frame
empty state has no motion, animator transitions use the open bool parameter too, and no nothing tells the door to open, as I know,I'm sure about these
also in the first frame that Update runs you tell it to open
yes I tell it to open if the player interacts with it, but there it opens without me wanting to do so
There was no use of Update() in the code sent last?
you just said that code was in Update
the OpenDoor() function gets called everytime the player interacts with the door in another script so this basically is in an Update() function
I changed the script too, the other one was too complex for nothing, I use has exit time set to 0.75 instead
did you check if that is working correctly? Select the door to see the animator state and see what happens when you press play.
You can also add logs to know when the door is told to open (or use a debugger)
yes this works well, I'm debugging everything and there are no issues with it
well something is wrong clearly and im out of ideas
yes and so am I lol...
and when I tell you there are no issues with the things you mention, I'm sure about what I'm saying,I'm not lying to you you know
have you actually verified using logs and/or breakpoints? because your assumptions could be wrong
for me, as there are no issues in the scripts, it probably comes from the entry state in the animator state but there are no animation clips assigned so its weird
yes Im using logs in the PlayerInteraction script
then show it
and in this one I'm not, but as it's some kinda short code,I didn't think it was needed
didn't think it was needed
when debugging it is almost always needed so you aren't making incorrect assumptions
debugging is always needed u mean?
i mean logs and/or breakpoints are always needed when debugging
"What is telling my door to open?"
add a breakpoint and find out!
add logs to the OpenDoor method, ideally useful logs that provide relevant information and not just a useless string that tells you the method has been called
to be honest, I don't know what kinda logs you tell me to put, but I've just added a string log that u called useless, and what I know is the OpenDoor() isn't getting called at the beginning of the game
then congrats, it isn't this code doing it
it's most likely either some other code or your animator setup
the problem most likely comes from the entry state
yes
it's the animator setup for sure
bruh, I was so much improving, making cool things and now I can't animate a door, my brain is washed
then you need to show your actual transitions
here it is, the transitions conditions are open == true if it's towards the open state and the other way around for the other state
that does not show the transition, that shows you have selected a transition and are looking at the animator parameters
you have conveniently cropped out the actual important information which is on the right in the inspector window
conveniently???
ITT we learn about sarcasm
anyway, the only way for it to transition to open is if your animation parameter is set to true. so something is setting it true somewhere, whether that's from being true by default, or some code somewhere, that is the only way this is happening
okay sorry
as you can see here, it' s set to,false by default
and there is nothing changing it.... in any scripts
isn't it possible to be the entry state?
I know this shouldn't be it as there is no motions/animation clips
don't make assumptions.
but this is the only thing left...
if it is an empty state then it is literally impossible for it to change the value of your animation parameter. something else is doing it.
it's a project I've made 2 days ago, there are like 5 scripts max, 3 of them are for the player Controller and the 2 others are the one I showed u, and it seems to have nothing setting the bool to true...
yea
then prove it. prove that the bool is not true
whenever i download the unity assistant i get these errors and it ruins the whole project i dont understand
select the object that uses this controller
I am
i couldnt solve this issue
Im going to rec and show u
show that object's inspector because this isn't showing the object in any state
does it show any revelant informations? or did I crop out the actual important information again? if I did,I'm really sorry I'm trying my best
are there any components on that pivot's parent object?
@slender nymph can you check the screenshot i sent up above
don't ping people into your issues. your question is also not an issue with your code and therefore does not belong in this channel
where does it belong
keep it in #π»βunity-talk where you were already receiving responses
point to where i was being rude
i'm not going to offer empty platitudes just to soothe your ego
ego
review the #πβcode-of-conduct
can you reread your messages and think if there was a nicer way to say the things you said?
Yes an animator only, which is the one I showed you
so the pivot object's parent also has an animator?
No, itβs just an empty gameobject that has all the doors
i am referring to the one between the "doors" and the "pivot_1" object
All the doors have a pivot Parent gameobject which has the animator component with the animator controller that I showed you and they all are the child of the doors empty gameobject
Oh yea youβre right Iβve changed itβ¦
your hierarchy goes doors > Wood Door_1 > pivot_1. I am asking about the middle object
The one above is the whole door gameobject, which contains the pivot + frame + door
The pivot is the parent of the door as the door is the only thing that should open and close, the frame is the frame, so around the door, and both the frame and the pivot are the child of a parent gameobject which contains the whole door, and then all those door containers so the doors are the child of the doors empty gameobject
I am asking if that object has any components
Also, you have confirmed that you did not mix up your animations, right?
There is only one animator and heβs always on the pivots
It simply has a mesh renderer
i solved it thanks for nothing buddy boxfriend
no need to be rude
Cool so now you know that you don't need to ping random people and demand they solve your problems for you. You can just work on it yourself.
An important lesson
indeed
the point is, i read his older messages and he is very unpolite
i did not say those things because he didnt help me
no one has to help no one
and he was already on the chat so pinging is not the problem
not against the rules
Pinging someone you're not in a conversation with is the problem
and is against the rules
#πβcode-of-conduct
Yes it is
Note that I said animations there, not animators.
Hey everyone! Not sure if this is the right place to ask, but Iβll give it a shot.
Iβve been using Screen Space - Camera for my UI for a while, but I recently switched to Screen Space - Overlay. That change ended up breaking some of my mouse position logic.
From what I understand, I should now be using Input.mousePosition, which seems to work, but Iβm not entirely sure if thatβs the correct approach.
I also have an icon that follows the cursor with a set offset, but the offset now seems to be in pixels, so it changes depending on the screen resolution.
If anyone has some advice or resources on how to handle this properly, Iβd really appreciate it!
You can convert from screen to viewport position to make it consistent.
Or use screen width and height to adjust this.
Yes I didnβt mix them
Ohhh my bad I pinged you, didnβt intend to do soβ¦
Sorry
It's only against the rules to ping people you aren't currently in conversation with
Anyway, just to confirm, this issue affects all doors with this animator+animation controller, or only this one?
this code looks like it'd operate perfectly fine, so why is it giving me spread that looks like the second image?
im wondering for the access control cloud code , json thing is this a valid urn ? ""Resource": "urn:ugs:cloud-code:/v1/projects//modules/","
cloud code is but i cant find about modules
is that
- What is the value of spreadOffset?
- Are we looking at multiple shots here?
- Are you moving the camera at all while shooting?
Also you could just do playerCamera.transform.forward no need for the viewport point thing
- it says in the screenshot
- do you mean simultaneously or over time?
- no
another reason that old tutorial was a goddamn scam
- Where?
- either
- 4th line - Quaternion spreadRotation = Quaternion.Euler(spreadOffset.x, spreadOffset.y, 0);
that doesn't tell me the value of spreadOffset
that tells me that your code is using the value of spreadOffset
oh wait
I want to know what that value actually is
wait not that one the line above it
ok what's the value of spread
that's the one I change between weapons, it was 10 in the screenshot
Can you show the shooting code that uses this function?
Apparently neither 1 or 0 correspond to any id on the animator, even tho it has quite literally just one bool, am I missing something? How do I know the id of the parameter?
You use the string version of the function
Or you use https://docs.unity3d.com/6000.2/Documentation/ScriptReference/Animator.StringToHash.html to get the int hash
(which is what the string version of the function uses under the hood)
Shouldn't this work and be faster than looking for a string? Or I just don't understand this?
You can use StringToHash to get the int
then you can use that int and it will be faster yes
The animator maps parameter names to ints with that hash function
But they are not ordered ints? Just random values that I don't know?
exampkle:
int jumpParamHash;
void Start() {
jumpParamHash = Animator.StringToHash("Jump");
}
void Jump() {
animator.SetBool(jumpParamHash, true);
}```
Using a hashcode (int) value for the parameters gives you the speed of the int parameter with the stability of the string parameter names
otherwise if you rearranged the parameters suddenly your code breaks, as do parameter IDs being saved to files, sent over networks, etc
they're neither random nor ordered.
If they are not ordered they feel 100% random for me tho
Oh, wait this is a Class level reference? Not isntance? So it searchs on all animators???
It's neither
the hashcode function is a static function
it's just based on the string
hashcodes are 100% stable, that's kind of the point of them
definitely not random
The Hascode, yes, I mean, the "Animator" part
Where is it looking for that string?
Can I not have two animators using the same string?
it's not "looking" anywhere
it's running a hash function on the string data
Not an issue at all
Perhaps it's time to do some reading on hash functions and their uses:
https://www.geeksforgeeks.org/dsa/hash-functions-and-list-types-of-hash-functions/
that's a bad primer actually
delves into jargon too quickly
Yeah, I could read that 20 times and I wouldn't get anything out of it
maybe ask chatgpt about hash functions a bit
I just wanna know, here, for example, it is returning me a hash for that string; that string can be in many animators, but I am not referring any in particular, so, what is that hash code asociated with?
the hash code is associated with the string you put in
that's all
"Play Fadeout"
Ooooh, now I get it
the hash function maps strings to integers in a consistent way
But that's basically the same than looking for a string but with extra steps right?
Mmm lets say you are pulling a string animation bool reference from two scripts. A hash would let you target one more specifically.
But its more like a unique identifier
it's more performant, like you said
Yeah, yeah, I thought it was getting a direct reference to the parameter in the animator as an int in a list
But I guess it just generates a hashcode for a particular string and you just type that isntead
But that just seems worse to me
I would've assumed it was an int based on order, but a hash makes sense.
You could probably go your whole career without needing to use one, but i find i use them a lot more with custom asset importers etc.
It would have then to get the string from the hashcode, then search by string, instead of just searching by string which was the part I was trying to avoid cause that's usually kinda slow
I am confused by how so many parameters on some components have to be accesed by string search instead of having a direct path
But what do I know, I am total newbie
animator is special and yes the string stuff is annoying
similarly, loading by string / path values
you never go from hashcode back to string
the params are stored by hashcode
when you use strings it goes to the hashcode then to the param
but the hash idea is probably as good as you're getting. Ideally I would like if the animator exposed the enum that was created inside of the blend tree
I personally wouldn't worry too much about that unless you really need to zero in the performance. 95% of performance issues will come out of your rendering, physics, disk ops and things of that nature.
Sometimes the readability is more important than the small performance gain.
But it is highly valuable knowing how it works, should you find out you do need to do it at some point. Imho anyway.
Ideally I'd want it to store the parameters inside an ordered list and just let me pass the index directly; it would also avoid any renaming issues
Chage the order, now your index is wrong in all usecases. Meanwhile the hash won't have that problem and is unique to that name 
Ideally you want both, I am trying to avoid going for the "clean enough" route as much as I can cause that's just stacking shit for the long term, and if you ever have to come back it's 10 times worse
I feel changing the name is something you would want to do way more often than removing previous values on the list, but, yeah
You usually add more, but do not remove that many
In some cases, but not really in this case. The request is miniscule in the grand scheme of things. Its far more valuable early on to get something playable and find the actual pain points. Otherwise you'll just perpetually optimize something with no real measurable impact.
I mean, if you are applying these changes in hundreds of animation controllers in an update loop - yes its going to be a problem. But setting a bool is probably being done once in a few seconds to a single controller.
You can also add another layer and map an enum in your script to that string value, so you'll just end up modifying that value inside of the enum
but the string to hash idea is very similar and I would just do that
i have a chunked world built with an oct tree and I am currently bottle necked by the traversal i do every frame to check which chunks need to be loaded. The traversal itself is already efficient but because its called every frame it drops the fps. What is the solution to this?
i could run it on a seperate thread but that requires locking the world too much and the fps drops would still be present
the traveral is for every node that intersects a given spherical area, ensures all child nodes exist down to leaf size (1 chunk). For each missing leaf chunk within the radius, it queues a ChunkRequest if itβs not already loaded or being loaded
so it does a ton of extra work because almost all chunks are already loaded but i dont know a better way
Have you run the profiler?
to find what
to find the bottlenecks in your algorithm
the bottle neck is the algorithm itself, finding microoptimizations isnt gonna help
How do you know what is and isn't a major or micro optimization without using the profiler?
Profiling is step one of any optimization
yeah ive profiled it and done the micro optimizations
Can you show the profile?
i dont have it no more
make a new one
mk
showing the code will also be helpful of course
- What do you mean by "not working"? What is it supposed to do that it's not doing?
- Why do you have
[SerializeField]on your "DealDammage" method and your "heal" method? Thtat doesn't do anything on methods
Am I inter rupting something
nah u good
π 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.
Ok
What is the code meant to do that it's not?
It is souposto deal dammage when you walk in to it but it isn't detecting that it is walking into it
I'm bad at spelling
Why are you using Console.WriteLine(collision.gameObject.name);
For Unity you need to use Debug.Log
That is what vs said to do
Sounds like probably VS is not configured properly for Unity
Or it just gave a bad AI suggestion
that you followed
- Are you sure the player collider object has the tag "Player"?
- Are you sure there's an object with a trigger collider that also has the script with the OnTriggerEnter?
The first step would be fixing your log statement
and running the game again
and seeing if it prints
if it doesn't, you've messed something up in the scene setup
It's my first time chatting here, but I just wanted to say that I took 2h to find out that my project had a problem bcs I forgot to put "=" in playerRB = GetComponent<Rigidbody2D>();
I love programming
(You are running the game with the Console window open, right?)
yes
Part of this is that you haven't developed effective debugging skills yet.
It's fine to make mistakes but you didn't know how to find it quickly.
@frank rover have you checked these?
yes
Have you changed the line to Debug.Log? Does the debug statement execute?
your player is missing a Rigidbody2D
A Rigidbody2D is required for OnTriggerEnter2D
it could be there and just not shown right?
could be, sure
now it prints
i'm guessing it's not though
I got my first job as a unity developer this week and i'm having a hard time having to learn all by miself Unity, maybe that's why people shouldn't lie on the resume lol
Also canTakeDammage is set to false in the editor so DealDammage is doing nothing
(fy it's spelled "Damage", one 'm')
No worries, also I know it's not what you were asking for but just fyi Dammage -> Damage, Ammout -> Amount (I assume) (in the heal function)
I'm having an issue with raycasting, the firepoint -> raycast end works fine if i'm shooting something far away but when I'm shooting up close or on the ground then there's an issue
π 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.
sec
var weaponEntity = SystemAPI.GetComponent<ProjectileWeapon>(player.ValueRO.ControlledCharacter);
var weaponLtw = SystemAPI.GetComponent<LocalToWorld>(weaponEntity.WeaponEntity);
float3 firePoint = weaponLtw.Position;
var cameraTransform = SystemAPI.GetComponent<LocalTransform>(player.ValueRO.ControlledCamera);
float3 cameraForward = MathUtilities.GetForwardFromRotation(cameraTransform.Rotation);
var projectileEntity = ecb.CreateEntity();
int vfxIndex = bulletManager.Manager.Create();
var rayLength = 200f;
var rayStart = cameraTransform.Position;
var rayEnd = cameraTransform.Position + cameraForward * rayLength;
var raycastInput = new RaycastInput
{
Start = rayStart,
End = rayEnd ,
Filter = CollisionFilter.Default
};
PhysicsWorldSingleton physicsWorldSingleton = SystemAPI.GetSingleton<PhysicsWorldSingleton>();
var hits = new NativeList<RaycastHit>(Allocator.Temp);
physicsWorldSingleton.CastRay(raycastInput, ref hits);
Debug.DrawRay(raycastInput.Start, raycastInput.End);
float3 dir = math.normalizesafe(raycastInput.End - firePoint);
ecb.AddComponent(projectileEntity, new FirePointRaycast
{
VFXIndex = vfxIndex,
StartPoint = firePoint,
EndPoint = raycastInput.End,
Direction = dir,
Speed = 100f
});
that's where i'm sending the first ray from center camera
private void Execute([ChunkIndexInQuery] int chunkInIndex,
RefRW<ThirdPersonPlayerFixedStepControlSystem.FirePointRaycast> ray,
Entity entity)
{
float3 currentPos = ray.ValueRO.StartPoint;
float3 newPos = currentPos + ray.ValueRO.Direction * ray.ValueRO.Speed * DeltaTime;
bool reachedEnd = math.dot(newPos - ray.ValueRO.StartPoint, ray.ValueRO.EndPoint - ray.ValueRO.StartPoint) >=
math.lengthsq(ray.ValueRO.EndPoint - ray.ValueRO.StartPoint);
var hitList = new NativeList<RaycastHit>(Allocator.Temp);
var input = new RaycastInput
{
Start = currentPos,
End = newPos,
Filter = CollisionFilter.Default
};
if (PhysicsWorldSingleton.CastRay(input, ref hitList) && hitList.Length > 0)
{
reachedEnd = true;
}
hitList.Dispose();
var vfxIndex = ray.ValueRO.VFXIndex;
var vfxData = BulletManager.Datas[vfxIndex];
vfxData.Position = newPos;
BulletManager.Datas[vfxIndex] = vfxData;
if (reachedEnd)
{
Debug.Log("Reached End");
BulletManager.Kill(vfxIndex);
Ecb.DestroyEntity(chunkInIndex, entity);
}
else
{
ray.ValueRW.StartPoint = newPos;
}
}
and i'm moving the second raycast from fire point to the center camera end raycast by the speed
float3 newPos = currentPos + ray.ValueRO.Direction * ray.ValueRO.Speed * DeltaTime;
another gif showing the ray debug in the sceneview
not sure what's the issue :/
This is #1062393052863414313 code
really not for the beginner channel
ah thought i'd post here since it's mostly math related
fixed it, my issue was when I casted the first ray here physicsWorldSingleton.CastRay(raycastInput, ref hits); I didn't check if I hit anything so I could set what I hit to my target position
Does anyone know a way to deform a plane so that it conforms to the shape of a modified terrain in Unity?
move its vertices towards the terrain vertices or a raycast hit point position
all doors, and also sorry for the late response, I had to go to sleep as I had school
@slender nymph as I'm really clueless, I asked chatgpt and he told me the problem comes from the empty state and I should make "close" state as the entry state
well, that doesn't change anything
maybe don't use chatgpt for stuff
and what should I use
what was the issue you had?
it's sounding like an animation issue rather than a code issue, but i don't have full context
all my doors are getting opened at the beginning of the game, when I run it
yes it is for sure
all the doors have no scripts, no interactions, the only thing present is an animator
ok so why are you here
I'm going to show you my animator wait
well, think a little, go up in the conversation, figure out why I've started the conversation here, and why would I want to continue the conversation with someone I was talking with in a different channel
theres extended convo from earlier
that doesn't excuse using the wrong channel, no
that kinda does if I didn't know what the issue was, and I don't think you complaining about something you don't know is code related neither
conversations with specific people don't really exist - or well, don't need to exist - in these support contexts. what matters is questions, and the questions need to be in the right place
you just said it's not code related, so this channel is the wrong place if that's the case
it does not excuse it. it can be an understandable reason, sure, but if you've narrowed it down to the point where you know what the topic of the issue actually is (or if someone has told you), and you expect prolonged discussion, you should switch to the appropriate channel
is anyone familiar with graph toolkit if so how do u set the ouput port values of a node
I'm currently working on a tile generating function which determines which type of tile is spawned and passes it to the generator function
my question was. since this script can run pretty often (everytime you dig down) it can be abit heavy. Does adding return early to it stop the rest of the code from running hence increasing performance?
//if spawned tile is dirt, don't assign anything
if (randomTile == 1)
{
//Generate dirt
GenerateTile(x, y, tileBase[1]);
return;
}
else
{
//MinMax spawn position
int minFt = tileBaseManager.dataFromTile[tileBase[randomTile]].minFt;
int maxFt = tileBaseManager.dataFromTile[tileBase[randomTile]].maxFt;
//Can only spawn between tiledata fts -4 because spawner is 4 tiles below - 1 for clarification
if (ft > tileBaseManager.dataFromTile[tileBase[randomTile]].maxFt + spawnOffsetPos - 1 && ft < tileBaseManager.dataFromTile[tileBase[randomTile]].minFt + spawnOffsetPos)
{
//SpawnRate
int spawnRateNum = Random.Range(0, tileBaseManager.dataFromTile[tileBase[randomTile]].spawnRate);
if (spawnRateNum == 0)
{
//Spawn tile
GenerateTile(x, y, tileBase[randomTile]);
return;
}
else
{
int emptyTileRate = Random.Range(0, 16);
if (emptyTileRate == 0)
{
}
else
{
}
}
}
which return you talking about ?
it will stop whatever is underneath sure, if you worry about performance you should profile and get some numbers and compare
for some reason the script didn't properly show up but here it is. i added some early return ends when i could. is this a nessecery and good practice if i don't want rest of the script to run
//if spawned tile is dirt, don't assign anything
if (randomTile == 1)
{
//Generate dirt
GenerateTile(x, y, tileBase[1]);
return;
}
else
{
//MinMax spawn position
int minFt = tileBaseManager.dataFromTile[tileBase[randomTile]].minFt;
int maxFt = tileBaseManager.dataFromTile[tileBase[randomTile]].maxFt;
//Can only spawn between tiledata fts -4 because spawner is 4 tiles below - 1 for clarification
if (ft > tileBaseManager.dataFromTile[tileBase[randomTile]].maxFt + spawnOffsetPos - 1 && ft < tileBaseManager.dataFromTile[tileBase[randomTile]].minFt + spawnOffsetPos)
{
//SpawnRate
int spawnRateNum = Random.Range(0, tileBaseManager.dataFromTile[tileBase[randomTile]].spawnRate);
if (spawnRateNum == 0)
{
//Spawn tile
GenerateTile(x, y, tileBase[randomTile]);
return;
}
else
{
int emptyTileRate = Random.Range(0, 16);
if (emptyTileRate == 0)
{
}
else
{
}
}
}
early return has multiple benefits yes, the second one you have is kinda useless. Nothing underneath it unless you're omitting more code.
actually both are kinda pointless rn (unless you have more code outside these if)
They can run pretty often which was my concern, i had to optimize the code to make my game playable again.
but yeah i've added alittle more below the Spawnratenum
//Generate special tile
if (spawnRateNum == 0)
{
//Spawn tile
GenerateTile(x, y, tileBase[randomTile]);
return;
}
//Generate dirt or empty tile
else
{
int emptyTileRate = Random.Range(0, 16);
if (emptyTileRate == 0)
{
//Generate dirt
GenerateTile(x, y, tileBase[1]);
}
else
{
//Generate empty
GenerateTile(x, y, null);
}
}
if you say it''s pointless i should like you said probably
test out if theres any
difference
the else is not gonna run anyway cause if spawnRateNum == 0 is true
so return just stops the rest of the entire function you have this code in
hello, listen I have a raw image in the UI and I want that if I click in certain position, it make something different than if for example I click in other object
Im not sure how to do that
you should not mix physics with UI elements
Yeah souldn't use box colliders on ui
if you want different sections to click on you can just make addtional Images as hitbox, and turn the Alpha down
Oooh I see, now that you mention it. It is possible to make that with buttons?
sure you can make them buttons too
the concept is the same, you can turn down alpha so they're still clickable but see through
thanks, ill try!
I have a slider that is calling ChangeBitrate() as shown in the attached image. The code is as simpe as can be :
public void ChangeEncoder(float value)
{
Debug.Log("Changing Encoder to: " + value);
}
It runs on change but only passes the value 0. I have this exact script working on another element without issue. The only thing I noticed strange is for some reason it is showing an input within the "On Value Changed" editor component...I don't know why it is showing that...it is set to 0
link it as a Dynamic variable
you should see the same function in the context menu and should say (dynamic) next to it
Hello can somene pleas check my code if it si right https://paste.mod.gg/ksiwnziyjeog/0 i was trying to make working save sytem but is is not working and i dont know why when i save palyer position and go back to the menu a spawns at diffrent position than i saved
A tool for sharing your source code with the world!
Ahhh...ok...I see that it appears twice in the list.
Will test now
@nav : Thanks so much that was it
how you call Save
also consider putting more logs / make them in english when you request help so people can also understand what you're logging
ok i will change it to englih
english
https://paste.mod.gg/kejkrtgwlmue/5 here repaired
A tool for sharing your source code with the world!
so what are the results of the logs?
ie is Load / save printing etc.
Loaded postiont in fist time netering the game is Loaded player position: (-30.26, -13.17, 0.00) Current player position: (-9.39, -13.17) and saved position is Saved player position: (-9.22, -13.17, 0.00) and if i go back to menu and to the game the position is Loaded player position: (-9.22, -40.01, 0.00)
you should turn off "Collapse" in your inspector
it makes it difficult to tell what order your logs are printed in
yeah but if i turn it off the there are 2 audio liseners in you scne mesege wont stop spaming
so get rid of one!
better?
So i'm seeing here that the saved position is always being loaded properly
The part where it's changing is after loading and before saving
so the position is being modified in the game itself or in the saving process
i can send you the video how it looks in game but dicord wont let me send it if i dont have nitro so are there other ways to send it?
I am incredibly green to coding and programming any good video series to watch I want to learn and get at least decent at it?
there are beginner c# courses pinned in this channel and the pathways on the unity learn site are a good next step to learn how to use the engine
Hi all, I'm trying to learn the cloud code stuff and in the last day or so I can no longer see my CloudCodeService logs in the Dashboard -> CloudCode-> Logs,
but... If I go to Projects-><ProjectName>->Theres a banner for Diagnostics(View Diagnostics)-> Then finally -> Logs. Then I can see the cloud code logs i used to see in CloudCode-> Logs...
Anyone know if this was changed or if I might've hit some weird button somewhere in the last 2 days..
I hope that made sense π€¦ββοΈ
cant there be error in that i am saving it in Vector 3 and not Vector 2?
Hi.
We take input in update and use that to move using fixed update is using rigidbody.
so taking bools in update, checking in update and then reseting their values.
@swift elbow
Any easier way? New Input system does it well?
add a debug log inside of that method
Isnt OnMouseDown only called when the mouse is over that hitbox / ui element
both input systems are fine
yes
oh the collider needs to be a trigger collider
I mean its annoynig to reset bools after everything happens
I get jumppressed = true in update
after jump i have to reset it to false.
@rough granite I really dont know π
that is common practice
oh okay
before i just did everything in update
@swift elbow so you mean i should click on "IsTrigger" ?
Just called jumppressed = false; after the jump called is called
isnt that what they said?
@swift elbow it does not work and nothing is printed in the console :/
I mean i guess but their wording made it sound like they go in the inspector and click the box to change the value
are you using the old or new input system? OnMouseX messages only work with the old system
What is with you mentioning (@) people to reply?
that is not the case.
i realized i read the AI google response that said that, not the docs π€¦ββοΈ smh my head
i am restting it in 3 areas. thats normal ?
Yeah yeah
In this case you can just reset it once somewhere inside the if(jumpPressed) block
No need to do it in 3 different places when it is done anyway
{
transform.position += Vector3.right * speed * Time.deltaTime;
}
if (Input.GetKey(KeyCode.LeftArrow) || Input.GetKey(KeyCode.A))
{
transform.position += Vector3.left * speed * Time.deltaTime;
} ```
Anyone know how to smooth this movement a little? (as in rounding the movement by introducing a bit of acceleration (and deacceleration, havent rlly decided on how that would be implemented tho))
I'm very new.
You could look into Mathf.Lerp/Mathf.SmoothDamp
Mathf contains alot of calculative methods off the bat that you can use for alot of stuff.
I hehe, yeah, i was typing an example. but if that's not what you want
i can stop.
You can keep doing that, I'd love an example
Alright.
also if you want collisions to work you're not gonna want to use transform.position for movement (if you want the player to collide with walls for example)
Ohhhh, didn't know that. I'm making a brick breaker type project and the provided code is for the little bar at the bottom that bounces the ball!
in that case your current one might be fine
Yeah I think the best idea would be to just implement a way for the gameobject to know if it's gone too far to one side
float playerSpeedX = Mathf.SmoothDamp(playerSpeedX, playerMaxSpeedX, ref velocityX, acceleration); //this also contains more methods which aren't required but grant you even more versitility
//If that's abit too much here's a another example
//Progress repressants the value that's gonna be applied in between playerSpeedX/playerMaxSpeedX
//and progress is a 0/1 between value. if progress is 0.5f then players speed becomes 2.5f
float playerspeed = 0;
float playerMaxSpeed = 5;
float playerSpeedX = Mathf.Lerp(playerSpeedX, playerMaxSpeedX, progress)
//If you're familiar with vectors yet you can also use
//Vector3.Lerp
//Vector3.SmoothDamp
Yeah. although you can just use rigidbody.linearVelocity which handles physic movement
for you
instead of manually moving the object
RigidBody rigidbody;
//this gives your object velocity movement
rigidbody.LinearVelocityX = 3;
//Alternatively this gives you more of a car like force that can accelerate.
rigidbpdy.AddForceX(3);
Mathf.SmoothDamp is the way to go for smooth moment or variable changes. that''s an good call
alright, i kind of get how it works.
stuff like the first example do go into the update() code block, right?
stupid question
Yeah everything has a logical reasoning. to calculate movement you would have to do that constantly
every frame
i plug the playerspeed variable in place of the speed variable I had, right?
Seems logical
Not sure. that depends on what your speed variable looks like
oh, then yeah
although probably specify if it's purpose is for x or y movement if you havn't already
You're defining the variable using the same variable you're trying to define in your example btw
I don't see how that would work??
That's how it works. I was skeptical when i first got into it as well. the first paramater repressents the current variable, that's just how it works.
you need a starting point which is your current speed and a goal which is the target speed.
are you certain thats how it works.
never seen any ide accept that
especially in the same scope
mine certainly does not
well that's how i handled it and it works perfectly fine.
what you have above and here are two completely different things
also why do you write "ref" in your example
The way you presented it puts the velocity setting in the same scope as the variable declaration which is not correct
it's a requirement for the SmoothDamp paramet. it makes the variable add on top of the last one, in this case with velocity
In my screenshotted code or the example i sent?
hmmm alright wait
In the example. Your screenshot is correct
i think we're just confusing him more.
that's what Magic was referring to