#💻┃code-beginner
1 messages · Page 245 of 1
the crosshair is not a child and its still acting like this
that line of code is nonsense
remove it
it's not going to do anything either since you're overwriting the rotation a few lines later with tf.rotation = Quaternion.Euler(0, 0, angle);
hi, can i somehow make a static vector3 get; set;? to save data for other scene???
While there's nothing inherently stopping you from doing that, static variables are not the way to go
Make an actual class to hold the data
ok now keep a reference to that class in either a DDOL singleton or a ScriptableObject
what's the syntax?
for what
umm... i think i forgot something
so..... i want to make a static vector3 in a static class and the vector will have 3 classes
ugh i want to pass the pos of 3 obj to other scene
and keep an instance of it referenced from a DDOL singleton or ScriptableObject
Yes I'm explaining the best way to do it
public static class Pdatas
{
public static Pdata Plane1 { get; set; }
public static Pdata Plane2 { get; set; }
public static Pdata Plane3 { get; set; }
public class Pdata
{
public int PosX { get; set; }
public int PosY { get; set; }
public int Rotation { get; set; }
}
}
instead of p1 2 3 i want to make a vector
it stupid because its easier with other method or?
Because static variables are a bad idea for many reasons. it will be hard to manage this way
static variables mean that you get one -- and only one -- instance of that data
single use
it's also annoying to serialize and deserialize static data
You will need to manage this completely manually
and yes serializing will be difficult too
um.. im not doing much with it, just single read in the next scene
You want something like this:
public class GameData {
public List<PData> Objects;
}
public class PData {
public Vector2 Position { get; set; }
public int Rotation { get; set; }
}```
yes
then you can keep an instance of GameData on a singleton or a ScirptableObject
Once you have the GameData, I think it would be fine to just stuff it in a static field to get it from Scene A to Scene B. You can build something more complex if you need it later.
anyway I don't see what the issue you were having was. Are you confused about the difference between a Vector and a List?
setting my camera refresh rate to fixedupdate fixed this
can somebody help me, the enmy dies but it stands back up no clue why, the death animation isnt looped
probably calling taking_damage_enemy state again by hitting it
have you disabled its colliders on death?
nvm was looking at wrong clip
nope how should i do that
How can I get an image of a 3D GameObject, the background must be transparent ? (I can choose the camera angle to take the 2D image)
is that the enemy death running again?
you probably need to disable transition to self
I have an extension if you're trying to take screenshots of scene objects for UI
I would like to!
it will give you transparent background or you can set one up
What does it mean to make a variable static?
means it will belong to the static instance of the class
fixed, was a mistake on the animation
all classes have static and non static part, static exists as a single instance, available through the class name
I have a dynamic RB (parent) and a kinematic RB (child). Both have and need a collider. If I addforce to the dynamic RB, it's still sometimes colliding with the kinematic RB, although the kinematic is a child. Are they not moved together?
by marking field or method as static you put it into the static part
nah they are separate bodies
if you want to avoid self-collision you can use layer based collision
Hmm so like there can only be one value of that variable?
only one can exist yes
in a sense yes, only 1 static class exists globally, it is created for you by the .net and you cant delete it
in the context of unity also you will not be able to set / see it in the inspector
hmm okay
so if a variable is public and static, anything can access and change that value
What's the suggested way to code bodies with their own colliders that sometimes get connected (and move jointly) and sometimes work independently?
depends on your game really , do you want it to collide with itself or not.
class Foo
{
public static int count;
public int nonStaticCount;
}
void Test()
{
Foo.count = 5;
Foo foo1 = new Foo();
foo1.nonStaticCount = 1;
Foo foo2 = new Foo();
foo2.nonStaticCount = 2;
Foo foo3 = new Foo();
foo3.nonStaticCount = 3;
// Foo.count is 5, the rest have unique values
}
Should not collide with itself, but with others. Think of building something out of lego pieces. Once you stick them together, they're a unit.
layer-based collision could work but
Hmm.. I want to generate a getter and a setter but also be able to set the value in the editor, but the issue is that it doesn't appear in the inspector. I tried making a secondary value that is accessible in the editor that gets applied to the getter/setter
like this
[SerializeField] float _decay = 1.0f;
public float Decay { get; set;} = _decay;
But unfortunately this is wrong.
tought of that, but if you build many independent lego structures, I need to dynamically create layers. that seems cumbersome.
[field: SerializeField] public float Decay { get; private set;}
does the set need to be private?
static members wont be shown in inspector, but
Oh- hmm I see...
no but why use a prop at that point lol
[SerializeField] float _decay = 1.0f;
public static float Decay {
get => _decay;
set => _decay = value;
}
this is a hack by the way
I'm not sure what you mean?
i dont recommend as a wide use pattern
how to properly duplicate an object?
problem with your initial example is that the value is only assigned at the object creation
wait I fixed the issue where it stands up again but how do i disable its collider and movement after it dies
oh my.. don't use GameObject.Find
or its not assigned at all, most likely its a compile error
Destroy(thecomponent)
this is my movement code, do i add a else if then destroy the component?
Well my preference is that it is set on creation or which value are we talking about?
why? :D the object is found and duplicates but not on the position i want
nah when u run the Die function or whatever
Destroy(ColliderReference); Destroy(this);// destroys the script, not the object
im becoming confused, you want to use static there or not?
because its slow and britle
Well I want to be able to change it in the editor and in game, but I have heard that it is bad to use public on variables?
depending on gameobject names is a horrible idea
and goes against the whole type-safety concept anyway
its a blanket advice that if not explained why, will lead you towards bunch of wrong assumptions
we can fix that later, please now i need to know why it doesn't duplicate on specified position
in short you by default strive to keep everything private, and resort to using public on things that are intended to be modified externally
I see
what are you trying to duplicate, its unclear to me
Well this value is intended to be changed
the assumption is - if its public it is an indicator of intent to be used and changed
a tree gameobject
My teacher explained it poorly
its not wrong or bad, its just a way to interact with APIs, that has to be designed carefully
so whats not working ?
putting the cloned object on specific position
your position is prob wrong then
Are you talking about changing it in the inspector?
Being public or private is different from being serialized or non-serialized
In the inspector and via external scripts
i don't think so since i am using that exact position on another object that sets correct
stilll doesnt work , i referenced the patrol script i use
Okay, so you have to either make the member public or provide a way to modify the member that's public.
The latter lets you control exactly how the field is changed.
wdym
public void SetAngle(float newAngle) {
angle = Mathf.Repeat(newAngle, 360);
}
for example
can i move to DMs?
make a thread.
you should destroy any scripts that you dont want to run after death, even if health too runs animation you dont want that too
does destroy(this) destroy the current script?
I understand, but this value doesn't need any checks or calculation to be set, I'll just make it public
yes I mentioned this already
replaced the green with my own version below, cringe or nah?
Yes when you should just use GetAxis
still doesnt work
Proper way of cloning gameobjects
what exactly "doesn't work"
i can show u my patrol script
are you getting error or what
no error juts a bug
the enemy dies , yet still patrols
after
i'll show u with a gif
oh yeah you're right
are you sure you destroyed that script ?
https://gdl.space/acaxozomom.cpp - enemy health script
https://gdl.space/meqivadipu.cs - patrol script
could u double check i aint too sure
you def have console error at runtime
patrolBehaviour and boxCollider are not assigned anywhere
wdym
i dont
hmm show me the console window when enemy dies then
theres this , but this is from ages ago doesnt affect enemy death
apart from that nothing else
this isnt the issue tho
no the whole Window
this is when enemy died?
yep
I need to test, somehow Destroy doesnt throw null I guess.
Okay either way, you havent assigned them
so it has no idea what to destroy
where do i assign it
the same way you assign stuff in PatrolBehaviour
[SerializeField] private then use the Inspector
sure
if (EnemyIdleTimer > EnemyIdleDuration)
moveLeft = !moveLeft; // only this line belongs to if statement check
EnemyIdleTimer += Time.deltaTime;
Btw when you Dont use brackets only the first line is part of the If statement block
now that it destroys it does this
also
in my game im going to have multiple enemies, doesnt me destroying the script for patrol affect all other enemies
you must have a script that is still trying to use it
no because ideally you are only destroying the component on the enemy
other enemies should not be affected from this single instance
Is PatrolBehavior on the Enemy ?
yes
i just tested something and duplicated an enemy and when i kill one, the other one complelety freezes
possibly because the patrolbehaviour destroys
that makes no sense , each enemy has their own version of each script
unless you made something flawed or global
i have one enemy type tho
is PatrolBehaviour on a completely separate prefab?
nope on the same enemy prefab
wait
mnightve found the issue
should the patrol behaviour scriptbe assigned to the prefab enemy?
if every enemy instance shares a reference to the same patrol behaviour, then destroying it will, unsurprisingly, leave every enemy without a patrol behaviour
so that means that it shoudlnt be inside the prefab?
no, it should be in the enemy prefab.
When you instantiate a prefab, any references within the prefab will point to the corresponding object in the instance
Your enemy prefab should look like this:
- PatrolBehaviour
- EnemyHealth
- BoxCollider2D
all of those components should be on the prefab, and you should assign references to them within the prefab
Is there a way to get the amount passed since start? or creation of the instance of a script?
record Time.time in a field
That looks fine. Each enemy will have their own patrol behaviour
I'll try it
^ this also you can record each spawn with DateTime.Now and compare time too
is this the in context of the prefab ?
What is a record?
yep
sorry I meant store
I mean, the keyword "record"
yep
thanks
just for the record, ive never seen this used anywhere before
then yeah others should no be affected
Destroying one enemy's PatrolBehaviour will do absolutely nothing to any other enemy's PatrolBehaviour
its very common in DBs
So is this how you are supposed to use the SmoothDamp? Cause I didn't find an example outside the Update method
does OnMouseOver just not work for tilemap?
You must repeatedly call SmoothDamp.
In a loop like this that runs each frame it's the same as update
did you put a collider?
So, yes, that looks fine
yes
yep it works now thanks
oh hi navarone!
thanks aswell
tilemap collider yes?
yes
might need to do your own raycast then
does the orthographic view change anything?
nah i think the issue is tilemap coordinates are not the same as world coordinates
isn't the tilemap collider one big collider?
yeah, I want it to send a result to the tilemap as a whole,
make your own ray then use tilemap.WorldToCell
but it won't send anything, debug doesn't even run, which means the funtion isn't being called.
any good tutorials?
probably. Its only 2 functions really
Why should I use record in this instance? am I not just storing a value in a variable?
no said to use record
What?
Yeah I meant that lol
var worldPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
worldPos.z = 0;
var cellPos = yourTilemap.WorldToCell(worldPos);
if (yourTilemap.HasTile(cellPos)) return;
//do something with tile here```
Yeah, but like, do I have to update the values given or does it do the transition itself based on the given aceleration?
thx so much!!
I don't quite get it
SmoothDamp takes the current position, the target, the current velocity, and a damp time.
would yourTilemap be a serialized field with the game object attached?
It returns the new position. It also updates the current velocity, which is passed by reference with the ref keyword.
You just have to call the method repeatedly
it would be a Tilemap type assigned in inspector
ok
@primal turtle what are you trying to do exactly , maybe there is something else
SmoothDamp has a deltaTime argument that defaults to Time.deltaTime, so you don't have to explicitly tell it how much time has passed if you're running it every frame.
hey its been sometime since i used unity i cant seem to find the navmesh window nor can i find the agent component...
just trying to know whether the mouse is on the tilemap as a whole or not
gotcha
this was supposed to be simple...
yeah tilemap.HasTile does that
So this is wrong then? Cause I am updating the transitionDuration
changing transitionDuration like that doesn't make sense
Did you install the ai navigation package?
the fourth argument is how long it should take to reach the target
This isn't a Lerp method.
You aren't telling it how far along you are.
nope. it was a package? damn alright thanks mate
All you do is tell it:
- Where you are
- Where you want to be
- What your velocity is
- How long you want it to take
it is now since 2022
It produces a new location and updates your velocity.
yup you can pass a Tilebase inside
so you can make your own tile
But, like it gets the position based on the time that passed since it was last called? Cause I don't get how is this working
oh wow okay havent realized its been that long lmao
I guess it technically does if you call it every frame
But it doesn't magically "know" how long it's been
hehe currently working on Grid rpg-ish / RE
Inventory system based on tilemap
That's what I was referring... so it just take starting point, end point and calculates based on the acceleration and the deltaTime where should it be, isn't it?
Damn wrong channel sry, ill repost
The magic is in the ref currentVelocity parameter.
If you have a known duration you can just use Lerp with an easing function
That lets it remember how fast it's going from call to call.
Or use DotTween which handles the whole thing for you
What if I call it again, but want it to reset to the ref?
I don't understand what you mean
"reset to the ref"?
Like, it remembers the acceleration it had in the last call; how do I tell it "nah, forget about that, we are doing a new transition"?
by using a different velocity variable
Nothing is stored in SmoothDamp at all. There is no static data here.
public class ExampleClass : MonoBehaviour
{
public Transform target;
public float smoothTime = 0.3F;
private Vector3 velocity = Vector3.zero;
void Update()
{
// Define a target position above and behind the target transform
Vector3 targetPosition = target.TransformPoint(new Vector3(0, 5, -10));
// Smoothly move the camera towards that target position
transform.position = Vector3.SmoothDamp(transform.position, targetPosition, ref velocity, smoothTime);
}
}
if I wanted to use SmoothDamp for two unrelated things, I'd need two velocity variables
There is no magic. It doesn't run by itself, or remember values from call to call, or anything like that
Given a position, destination, velocity, and smoothing time, it gives you a new position and updates the velocity.
That's it.
nicee
I mean, if I call the Coroutine again, I am guessing the acceleration value is considered "new" and the ref is not stored from the last call
transitionVelocity is a local variable.
so, yes, the two enumerators produced by calling energyCounterTransition twice will have two different variables
If transitionVelocity was a field on the class you defined energyCounterTransition in, then two or more coroutines would wind up fighting over it.
hey guys, so i ran into a pretty big flaw in design, I have a movement state machine hierarchy, and the problem is the substates (idle, walk, run) ExitStates are not getting called when changing out of the parent grounded state. Is there a way i can ensure ExitState gets called 100% of the time?
I cannot tell whats goin on in this video tbh lol
Ill send code in a sec
But if you look close at the bool checks at the bottom, if i am walking and jump (leaves grounded state) the walking anim never gets called to turn off
But if i walk and then run it works bc i never leave grounded state
yeah the bools are runining the whole point of being in a single state
you need a cleaner way to activate the states
Yeah i knew i set it up in a bad way, i just cant find good documentation to follow
I just activate the animation on the EnterState, and disable it on exitstate
And trigger for jump
you're not using the built in scripts states right?
Uh, i think i am, i dont understand how to animator and state machine are supposed to work together, or if they do the same thing
I am using my script/state machine for the bool values
Are you saying i could just play the animation directly through code?
you can go into a state directly through code yes
Oh thank god
There's a custom class for animation states as well
Oh god no
yeah the build in script states
Please, no, not another wall😂
It's still c#
Ill check it out, i gotta get a faster workflow im moving at a snail’s pace😂
I attempted setting up github all yesturday and it didnt even work
there are plenty of tutorials on that system
It just gives you access to the animators call backs / events.
i read thru it, im lookin up statemachine behavior, is that specific enough?
is it okay if i use the obselete navmesh? i cant see the bake navmesh in the new one..
Should be
new one you should use navmesh surface
Hello guys (sorry if me english is bad), I want to make a weapon can bounce on nearby enemies, but I don't know how I can get the distance of the all enemies that exist in the camera so that is bounce. ¿How can i get the distance of the all enemies in the camera or scene? 😭
by "in the camera" you mean inside the view or just close enough to camera?
Vector3.Distance would work
if you mean in the view only probably do a overlap then calculate dot product to each one to see if its within a range "infront", or just use a boxcast forward
Is there a way to have a Serialized field which can accept one of two types of objects?
Without having a serialized reference to a common parent class and verifying in Start or something
How is the camera related? I would just use a physics overlap function to see who is nearby. Relying on the camera immediately makes this unusable by enemies
What are you trying to do? Sounds like abstract classes with child classes would be your solution here
Yeah that's what I'll do. I was mostly curious if there was another solution I was missing
Interfaces as well
It is possible in other ways but tedious to do with interfaces because you cannot drag in inspector by default
Oh you cant?
You would need custom inspector stuff for any other solution
can you expand on the desired result? "one of two types of objects" sounds like "just use end type"
My apologies then
i cant see where this navmesh surface is...? when i click the navmesh tab all i see is agents and areas
what does this error mean?
its a component now you add onto an object
so i add it to every ground object?
no you only need 1 of them
generic imgui errors that mean that some control is not reseting, is that from your code?
it has many filtering methods too like if you want only certain layers etc. @gilded verge
ignorance is bliss
i suggest you lookup the documentation on it
I gave it some thought and my desired result doesn't actually make sense.
I think this is just a general unity editor issue, but I have not seen it at all lately so it may be fixed in the 2022 version
ah so i just make a empty object and throw it?
This has been a thing for ages, no one knows
This is my camera. How the distances of enemies relate to the projectile of the weapon or the weapon itself.
You could put for example all the things you want to bake with a common empty parent then put surface on empty parent and select only child objects filter in it
Sr.x?
Hello
Im confused by what ur saying
you just need an overlap
that will check all enemies within a zone
then do a loop to each one for the bullet path or w/e ur doing
aah okay alright thanks alot
no probs. if you get lost here is the docs that explains all the modes
https://docs.unity3d.com/Packages/com.unity.ai.navigation@1.1/manual/NavMeshSurface.html
I'm going to try this, thank's.
I'm confuse with object oriented programming xD and i still don't know how the objects relate in the game.
yeah thats good imma need this thanks!
everything you do is an object in c#
But, the enemies have a distance in the map, the weapon have a distance to, but I don't know how to access the distance of the enemy with respect to the weapon or the bullet because they are different objects
hello, I have seen a lot of tutorial, but they don't seem to work. Do anyone know what version I should use?
yes thats why you do a physics query
to find all those objects with a range, once you do you do a loop to find the distance for example
This is one of the most vague questions possible. Tutorial for what, what doesn't work, version of what??
you can also make a bigger cast towards a certain direction and that gives you the hit distances as well
it was something about movement do you know how to do it?
the unity version would have no effect on the code / tutorial validity
unless ur looking at some js-like syntax which is very old
Look at the #854851968446365696 on how to ask a question, also look at how others ask maybe. No one is gonna play 20 questions to figure out how to help you
Still too vague to answer, but here
Bruh did you just toss him a flow chart
Actually you know what
Are you... unable to see it?
This is a damn good flow chart
ye
I was not asking you. But really?
yes
Maybe you need to download it? It's full resolution but discord sometimes compresses images
ok
Whoever made that o7
That's so beautiful i can look at it for hours
umm all?
well unityevent and c# are different thats why im tasking
im subscribing in a scene to send/receive some messages
unity
my movement script works fine but when i try and walk into a wall it starts glitching in and becoming jittery
private void Update()
{
direction = movement.action.ReadValue<Vector2>();
float sprinting = sprint.action.ReadValue<float>();
float currentSpeed = speed;
//changes which speed to use if player is sprinting
if (sprinting > 0)
{
currentSpeed = sprintSpeed;
}
else if (sprinting == 0)
{
currentSpeed = speed;
}
if (canMove)
GetComponent<Rigidbody>().MovePosition(GetComponent<Rigidbody>().position + new Vector3(direction.x * (currentSpeed * Time.deltaTime), 0, direction.y * (currentSpeed * Time.deltaTime)));
}
oh lord cache that rigidbody...
Do not use MovePosition and do not do physics in Update
It belongs in FixedUpdate
Move via velocity
MovePosition will happily move you inside a wall
so this?
rb.velocity = new Vector3(direction.x, 0, direction.y) * (currentSpeed * Time.deltaTime);
(in fixed update)
Do not multiply DeltaTime
Otherwise yes
Velocity is already adjusted to be per second
you mean use fixedDeltaTime?
Velocity is meters per second already
ohh ok
what is this error mean?
You're trying to use a type that doesn't exist
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 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.
you guys shouldnt have told me about a better way to do animations, i went from "i need some functionality and animation" to "ooo procedural animationnnnnssssss"
Nobody knows what Entity is meant to be, so we can't answer you
i dont know ether i followd a tutorial and got that error
you probably copied wrong like last time
Also, by sending a screenshot of the console window and not the error underlined in your IDE, it indicates that it's likely unconfigured. !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
• Other/None
hope not 😢 we spent good amount of time configuring it #💻┃code-beginner message
i fell hurast
the movement works but now if i move into a wall diagonally, the player stops moving entirely instead of just stopping moving in the direction thats going into the wall
I am facing this problem
it is shaking in bottom
if you u are doing 3D you can use character controller that gives you that sliding on walls behavior
can someone help me with this code?
i have the problem that i wanna split up the code of the X and Y axis because the gravity pulls my character and moves it across the map
im not finding the right way to implement animations into my state machine script... theres the blend tree and transitions with booleans, is there any other way?
using System.Collections.Generic;
using UnityEngine;
public class MouseY : MonoBehaviour
{
public float mouseSensitivity = 500f;
float yRotation = 0f;
void Start()
{
Cursor.lockState = CursorLockMode.Locked;
}
// Update is called once per frame
void Update()
{
float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity;
xRotation = Mathf.Clamp(xRotation, -89f, 89f);
Rigidbody.localRotation = Quaternion.Euler(xRotation, 0f);
}
}
Possibly due to friction? Hard to say without seeing the project
I was wondering if anyone has any good recommendations on a tutorial series for how to set up a 2D inventory system? been trying to set it up for a while but been struggling
that isnt possible
every inventory is different and people use many different ways to do it
instead of following a series, recommend you just learn what parts you will need and go from there
Yeah, they can be either super simple or complex af
yup start with a basic one list / dictionary
learn how to use a dictionary you'll make one quick
Ideally, don't have a resizable inventory, craft your inventory prefab beforehand and serialize the exact UI slots to the script on the editor.
okay thanks for the advice 🙂
Theres no difference between 2d and 3d here. An inventory can just be a list as others said. Consider things like do the user need to interact with the inventory for rearranging/dropping etc? Do they need to be able to interact with objects with different options? Is it just a place where they hold objects and the user doesnt need to touch it
i just completed a really in depth tutorial series on an inventory system, it took me a week or so of hours a day
If the user doesnt need to do much then it can be extremely simple
im remaking mine right now to make it less complex
this one is perfect, equipable objects, swapping, deleting yada yada. but it falls into "you need this for this to work" kind of thing. along the lines of what theyre saying
How bad could it have been?
hehehe
having different inventory types like equipment slots also adds some complexity since you're now making sure you can swap items into it
because inventory can have all item types, but each equipment slot can only have a single type
and if you've got drag/touch controls then you need to duplicate a lot of that logic
then you have your hotbar which you may want to store equipment on too so you can quick swap, but then you need to make exceptions for that too
me trying to make a Grid / resident evil style inventory using only tilemap 😅
oh no
im not finding much on coding animation instead of using booleans or blend trees
You can use bool but your flaw is activating them at the same time
huh
like two nodes being true at the same time?
so i could take the ground bool out?
2 bools of state both true = you're not in a finite state lol
shit nvmd, i got some learning to do
What you could potentially do is use Enum cast to int then use that to activate a state
so instead of bools use int coming from state
couldnt i just check if its in a state or not? that may be easier but it just made my perspective more confused haha
the flaw with what i have rn is its not calling exitstate from each substate method once it changes superstates
that would require a pretty big swich statement then disable all bools back to false even if it was never set to true
its not necesarilly leaving the substate, its more like turning it off or pausing it
and switching super states, and so the bool always stays checked until i enter the state again, then it fixes itself
thats why i dont think its good to have bools instead its more assured to use an int
so if i walk and then jump ill still be walking when i land but not move
okay, im not sure how to go about creating that
is your statemachine in code an enum ?
no
oh..
yea, its hard to tell what to do. theres too many ways to do the same thing
i wish there was a vc channel, problems would be so much easier to talk about
oh dang cause thats how I do mine usually and its simple to link it to animator
something like cs public enum States { Idle, Walking, Sleeping } public States statecurrent; void ChangeState(States state) { statecurrent = state; anim.SetInteger("state", (int)statecurrent); }
yea, i guess this one is supposed to be much more robust and modular or something idk
trying to make a game that is as clean and dry as i can get it. i figure if this is easier for more exp devs that me taking a really long time not rushing to finish at each step would soon get good results
I just use the most straight forward way until i need to expand, otherwise if i sit there thinking of every little Design aspect Ill never accomplish anything
my earlier projects were over-designed / overengineered when sometimes the KISS method works best
Lalala can’t hear you
i did that, but took note of what made it harder for me to continue, those things were movement capabilities, inventory system, saving, and procedural environment
now im trying to make sure or gauge how good i need these to be before i keep goin
those can get complex fast
ohhhh yea
i want to stick with just walk run jump, but theres also falling, which i am having a real hard time implementing
start with the enum and a switch statement and ur done 🤷♂️
how would i fall, only if the jump animation completed, im not on the ground, and its not gonna look funky if it hits .1 seconds or somethign of animation
statemachine is a concept not a particular way to do it
as long as you exist in a single state, you have a state machine
wha..buh.. ujwah
*windows xp restart
*windows xp loading
*windows xp loggin
would the enum and animations affect my movement scripts?
why would it
Why do you do hit.collider.gameObject == gameObject
also, I doubt you want a raycast, and instead want an OverlapPoint
i dont know, somehow my animations became physical and started bullying my movement
do you have root motion checked or animated the root bone/legs?
yea i went thru that dumpster fire, fixed that, but i still have the fundemental issue that my substate code doesnt complete if i exit the superstate
Depending on the genre and use, they would either affect or be affected BY the state machine. For example, in my rts game, the ai movement only runs when the state is correct. Animations vary by state, etc
But in a fps the state changes based on input
Why would an object want to hit itself?
Oh, every script that wants to be clicked does it's own raycast? Yuck
You should only raycast once from the camera and check if what was hit is clickable
why do you have substates already if you only had those 4 states or w/e
because later on, when i add attacks, death, swimming, flying if theres a need, transportation and even load screens, that enum list will get extra long
the what ifs i was talking about earlier
also those mentioned wouldn't need to be substates anyway
yeah but i got stuck once i wanted to add more than just jump, move, crouch, and sprint
your flying and swimming controls would probably not be the same would they
I have no idea. As I said, I would use OverlapPoint. And actually do some debugging beyond a single log
no not at all lol, but you wouldnt want to be able to attack an enemy if your dead, you dhave to check for that, or if you could use a power move only when your hurt and about to die, etc, theres alot i could do with it
im not doing it justice trying to explain it well but it has its benefits
if you're in a dead state you wouldnt be able to get out of it
unless you had some revive potion or respawning
like rn i can use it so when im in the air, or falling, i cant move the character
They weren't talking to you I think
it would be a bit different to code, maybe a bit more destructive than just not including it in what the player is allowed to do in that state
its only flaw is the user in this case is not smart enough to use it well XD
imo is better to start simple and add on from there complexity as you go than to start complex with so many options that you might not even need
Why the heck is my value going down? Isn't this supposed to go from first value to second value?
i know it has to do with the order that the switchstate is called, i think exitstate(); may be in the wrong place?
I am getting the error: 'ArgumentNullException: Value cannot be null.'
Relevant code segments:
//from a class of static functions
#nullable enable
public static Edge? getEdgeFromPoints(Vertex a, Vertex b) {
List<Edge> intermediate = a.connectedEdges.Intersect(b.connectedEdges).ToList(); // error here ^, making this list nullable does not help
return (intermediate.Count < 1 ? null : intermediate[0]);
}
// from my Polygon class
private void pointsToEdges() {
if (_borders == null) _borders = new Edge[_points.Count];
Edge? e;
for (int i = 0; i < _points.Count; i++) {
e = Geometry.getEdgeFromPoints(_points[i], _points[(i + 1) % _points.Count]);
e ??= (_points[i] + _points[(i + 1) % _points.Count]);
_borders[i] = e;
}
}
#nullable disable
Any ideas on why this is happening and how to fix it?
passing two fixed values into SmoothDamp is a bizarre and likely incorrect way to use it
which line ?
Look at the stack trace, and think about what's being passed to whatever it mentions.
Presumably Intersect, so that would mean b.connectedEdges is null
I changed it for debug purposes, it is still going reverse with the intended ones
List<Edge> intermediate = a.connectedEdges.Intersect(b.connectedEdges).ToList();
I assume so. I originally only had return a.connectedEdges.Intersect(b.connectedEdges).ToList()[0] but this also threw an error. Are all null values not equal?
Still does weird things with these values
Are all null values not equal?
I don't know what you mean by this
As I said, presumably (based on the limited info you have provided) b.connectedEdges is null. You cannot Intersect with null.
Those values are both fixed again, energy - energyGain doesn't change over this loop
The first parameter is supposed to be the current value, not just one value. That value does not change
Oh, ok, I see
If the parent is on a specific layer, are all the children automatically on the same layer if their layer is "Default"?
That worked, thanks.
no
No. If there's a rigidbody involved iirc its colliders will use the layer of the rigidbody, but I'd have to test it
hi! how do you print a texture generated on runtime to png and avoid compression? i'm using this method but unity will downscale the image to the default 2048 when the texture is actually +5000px wide
void SaveTextureAsPNG(Texture2D texture, string name)
{
// Ensure the texture is not null
if (texture == null)
{
Debug.LogError("Texture is null. Please assign a texture.");
return;
}
// Convert the texture to bytes
byte[] bytes = texture.EncodeToPNG();
// Define the file path using the provided texture name (in this example, saved in the Assets folder)
string filePath = Path.Combine(Application.dataPath, name + ".png");
// Write the bytes to a file
File.WriteAllBytes(filePath, bytes);
}```
did you set it higher res in the texture importer?
it is generated on runtime, am i supposed to tweak how i'm generating it maybe?
when you create texture you put large size ?
show how you create it
you mean this?
textureB = new Texture2D(textureA.width, textureA.height, TextureFormat.ARGB32, false);
so you're saying textureA.width is over 5000px ?
i guess i should add an extra argument for compression size?
yee, 100%
forgot if thats a gpu limit
nvm there is no argument for that
or system
for x32 is like 8k
yee for x64 is double
unity limits 16384 so its not that..
i think it is on the method, since it will also change compression so how is the texture defined seems irrelevant
where do you see the size stays at 2048 in the project folder?
? in the inspector, once the png is generated it seems to be proportionally downscaled to 2048 which is the default texture max size
because maybe the original is bigger but the texture importer was seeing 2048 since its default import size unless changed
but if you're saying the file itself on hard drive is 2048 capped then nvm that
nah i mean it is not even just the compression option but like it actually downscales the texture, probably when EncodeToPNG?
was checking but manual doesn't mention any limits of sorts
fixed?
yes, i checked with the explorer and it has the right dimensions, but on the inspector it will show the compressed dimensions directly
i'm so sorry
thanks!
im having a bit of a problem where im trying to combine the sliding and dashing statehandler daves code into one but idk how to do it without messing up with the sliding building up speed when sliding down a ramp , does anyone know how i can fix it?
also the vids if needed
https://youtu.be/SsckrYYxcuM?si=yUR_ATpbTYeIQCyp
https://youtu.be/QRYGrCWumFw?si=mVEcdJ93Ak0vKjIJ
ADVANCED SLIDING IN 9 MINUTES - Unity Tutorial
In this video, I'm going to show you how to further improve my previous player movement controller by adding an advanced sliding ability, that supports sliding in all directions, sliding down slopes and building up speed while doing so.
If this tutorial has helped you in any way, I would really ap...
FULL 3D DASH ABILITY in 11 MINUTES - Unity Tutorial
In this video I'm going to show you how to code a full 3D Dash ability in Unity. Including dashing in multiple directions based on player input, keeping the momentum after dashing and adding camera effects to make the dash feel more alive.
If this tutorial has helped you in any way, I would r...
so you're trying to slide while dashing ? i don't understand what you mean combine to one
no no , i mean like combine the code so it doesnt mess with eachother since daves dashing tutorial uses kinda the same SmotthLerpMoveSpeed function but its different for sliding , im not sure how i can combine them so it doesnt affect one another , cuz rn when sliding down a ramp doesnt build up speed like in this vid
this was before adding the dashing
idk how to combine them so they dont mess with eachother
not sure tbh
cause rn when im dashing , the speed doesnt instantly go away and lerps to the sprint speed or walk speed and when im sliding the speed doesnt build up as i slide down the ramp
so i think its confusing eachother
Drag is unrelated to friction.
yeah i realised
i just solved my counter movement issue
i just increase the drag
instead of adding opposite forces like i did before
i forgot it exists
Hello everyone! How can I ask an Object to rotate the same way as another in the Y axis, without it being it's child? Thanks.
Parent Constraint
YESSS I FIXED IT

jsut did this
How can I use that?
Add component -> Parent Constraint
Ok, thank you very much
Land is called only once when the player lands and HandleLanding is in update
how can i improve this?
its not really smooth
if you played muck or any games made by dani then you know that when you land the camera like goes down and then up
giving the effect of more realistic landing
im trying to achieve this
i did it
how can i attach ids to animator values?
im trying to use animator.SetFloat(0, rb.velocity.z); and animator.SetFloat(1, rb.velocity.x); but its throwing an error on the first line
animator.SetFloat("name", value);
i tried that too, and it didnt work :/ same error
well it has to
MissingComponentException: There is no 'Animator' attached to the "Empty Player Controller" game object, but a script is trying to access it.
You probably need to add a Animator to the game object "Empty Player Controller". Or your script needs to check if the component is attached before using it.
read the error
i have the animator on a child object, am i referencing it wrong?
how are you referencing it?
using System.Collections.Generic;
using UnityEngine;
public class AnimatorValues : MonoBehaviour
{
[SerializeField] private Animator animator;
[SerializeField] private Rigidbody rb;
private void Awake()
{
animator = gameObject.GetComponent<Animator>();
}
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
animator.SetFloat("animSpeedZ", rb.velocity.z);
animator.SetFloat("animSpeedX", rb.velocity.x);
}
}```
ahhh okay, thankyou
i figured using gameObject is for a game object not attatched to the object the script is on
u dont even need the gameObject
u could even do animator = GetComponentInChildren<Animator>();
yea i think i got in children and game object meanings mixed up
it fixed that issue, much more to follow
how is my rb.velocity.z value affected even if im not moving?
Can I make a ui element a raycast target/not a raycast target in a script?
im gettin really strange behaviour with transform.LookAt in 2D, im trying to point this [image 1] gameobject's Y axis towards another object, in theory my code [image 2] should work, but instead of of the expected behaviour, the object in image 1 rotates along the X axis and makes the Y rotation -90 or 90 ( depending on the position on the object i want it to look at ) all instead of just rotating it along the Z axis
ive tried every single Vector 3 direction, none of which provide the correct result
😭
ok so apparently transform.lookat sucks for 2d, hope unity one day releases a 2d lookat function
if anyone has the same issue, https://www.youtube.com/watch?v=1Oda2M4BoNs, no mebed to reduce chat clutter
I'm having trouble finding the method to destroy an array that exists, then recreate it with a new index (or alter the index range of an existing array)
sorry for the question but is there something wrong with this line? (line 72)
What is StarterAssetsInputs?
idk i downloaded it off the asset store 😭
Hmm, well the compiler doesn't know what it is
Check that your editor version is supported by the asset, and if it has any dependencies
ok thanks ❤️
Can I post my code here and ask for advice?
yep, amazing no?
what does the
normalized
do?
normalized returns the vector with a magnitude of 1
Hey guys, do you notice anything wrong with this because its not working as Intended. https://paste.ofcode.org/75KTTditbqdQ33Zx6GmUxm . The intention is to Instantiate a InventorySlot into the Canvas>Inventory>Viewport>Content> (this is hwere it spawns the prefab). All is good with the instatiating of the prefab. The only problem is it doesnt set the itemWeapons Data as it instatiates the slot. Is there something im missing here? Here is a video https://gyazo.com/07f4e334402617476f190fabd079f4be not sure if you can see but when I transfer from the chest it just transfers the slot not the itemWeapons Icon. Not sure why.
how do i make an object move along the Y axis, relative to its rotation?
this code makes it always go on the global Y axis rather than the local
transform.Translate(0f, Time.deltaTime * speed, 0f);
ah, thank you! :3
Hey guys, i wanted to have my game quit after the player gets a certain amount of points (ive set it to 1 temporarily so i can check quickly) but i cant get this code to work
This s a screenshot of the scoring system im not sure if im referencing it wrong in the gamemanager
Where do you increase score?
Oh, it's public static, that isn't good, but I guess you increase it directly somewhere else?
those two are different variables btw
This one perhaps?
if you want the static one you would need to call it from the class it belongs to
Yeah, just about to say, theScore in GameManager is completely different than the one in ScoreSystem
ah
Do not declase a theScore variable in GameManager at all
Reference it exactly like you do in CollectBottle
also cache that Text component
GetComponent every frame is insane
no need to store scoreText as GameObject , you can store directly as Text
If the first thing you do with score text is get a component from it why is the variable of type gameObject instead of the component you want
Oh man holy scroll lock that was an hour ago. Sorry for necroposting my discord didn't fetch new posts until after I sent it
So im new to coding and setting up a basic movement system and have the jumping down but when going to side to side I gain more and more speed but I want a consist speed. I use rig2D.AddForce(Vector2.left * _walkingSpeed) is there any way i can keep using AddForce?
After setting up VSC for Unity I always get this in front of every VSC file project I might try to run.
You either need to limit the velocity, or adjust the amount of force that you apply such that it doesn't increase your velocity beyond the desired value.
Figured it out. https://gyazo.com/b95aab00bd66411c0fa8e7a9578c04fd Needed to call for the data once re instantiated
It's probably an extension you have installed in VS code.
scriptcs??
What extensions do you have installed?
A lot of unnecessary stuff installed I see. I think Code Runner implements scriptcs and calls the command.
Honestly, I'd just use VS(not vs code) for unity, to avoid issues like that.
And C# in general.
Im not using unity right now. Im just testing out c# on its own
As I said "and C# in general"
I don't know this program doesnt seem to work that well either lol
but you need code runner extension to run the code right ?
Press the down arrow by the button, what does it say?
wait Did you make a new project or just a random .cs file in a folder?
You need to create a proper project. You can't just run a single file in C#.
There’s a wizard that walks you through it
Should go through the C# manual to learn properly:
https://learn.microsoft.com/en-us/dotnet/csharp/tour-of-csharp/tutorials/
random new project
Did this change or am I missing something?
You need to open the solution or project, not just a lone .cs file
But I wanna use c# without a unity project
Ambiguity between your class name and the static scene manager class?
You still have to make a new project in c#
No the error is: 'SceneManager' does not contain a definition for 'LoadScene'
Yea because it’s referencing the current class your in
Add the namespace path to the static class if you want to have ambiguous class names
It doesn't have to be a unity project. If you want to create a console app, it needs to be a console project.
Thanks for that. lol It would have taken me a while to spot it myself.
Awesome, you got this my guy!
did you stick the box on another layer now
i dont get why you use a spherecast for checking ground
why not have a gameobject with a circlecollider
Some people can't view embedded discord text files. Consider posting !code using one of these two formats:
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 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.
also why are you crossposting @queen adder
I didn't look at the code but is your 'box' tagged as ground/ground layer?
Is this from a Tutorial? I remember there is a bad one out there that has you make a class called SceneManager
I've been trying to figure out which one it is
Usually you want to avoid that (unless you mean a child positioned at the feet, which is ok) because then you will be considered grounded when touching walls or ceilings.
But really, casting or overlaps are generally the best for ground checking imo. Spherecast is great, but I generally use raycasting
Well I got the idea from a tutorial but this was way back(I don’t remember which one). I just accidentally made my class called SceneManager. So I changed it to MySceneManager.
Fair. Thanks anyway!
i mean the child method yes
Yeah, I generally find that suboptimal, but yeah that works for sure
idk, creating a spherecast every frame doesnt sound that viable either
Why? They are basically free, and with a layermask it's gonna be cheaper than validating collisions from a collider
People have this weird notion that casting every frame is expensive.
They really are not, especially ray and sphere.
Capsule and box become slightly more, but still EXTREMELY cheap
Sphere is pretty damn cheap, ya. It's one of the simplest queries you can do.
is there a way to like play as 2 people on one pc similar to roblox's
Yes
Local multiplayer
yea how do i do that?
Just have different input control different players
ok
I'm having some trouble with HTTP requests. I have a simple HTTP server running on my localhost on port 8888. My browser can access it just fine at 127.0.0.1:8888 but unity gives a 'Cannot connect to destination host' network error. Heres the code:
{
mouthMeshRenderer = GetComponent<SkinnedMeshRenderer>();
StartCoroutine("RequestValue");
}
IEnumerator RequestValue()
{
UnityWebRequest request = UnityWebRequest.Get("127.0.0.1:8888"); //sends http request --> php script reads sql database
yield return request.SendWebRequest(); //waits until request is done
string requestString = "testing string";
Debug.Log(request.isNetworkError);
Debug.Log(request.error);
if(!request.isNetworkError && !request.isHttpError)
{
requestString = request.downloadHandler.text;
}
Debug.Log(requestString);
}```
I saw something about insecure urls being blocked on a support post but they didn't elaborate. Are simple ip addresses like this blocked in unity?
Oh also due to a package I need to use as part of the project, I'm on unity 2019.4
I realized I might need http:// on my url to make it work, but that returned a different error: Curl error 1: Received HTTP/0.9 when not allowed
Okay I figured it out. So http:// was needed, but also, on my actual HTTP server, I forgot to add 'end_headers()' to the get request code, which meant it didn't send a status code. The internal cURL doesn't like it when that happens and assumes its an old version of HTTP I think
Is using raycast in the "update" function OK and not burden performance?
Go for it. Character Controller basically does a bunch of raycasting too
okay thank you
How are you attaching it to the hand?
_>
How? Are you making the cube a child of the hand though a script?
How is the PickupObject method being called?
It says 0 references above it.
Are you calling it from a Unity event or something? If not, you may just not be calling it.
Alright. Just to make sure, does the box follow the players movements when it's picked up? It's just not actually in the hand, right?
Does the box have a rigidbody and collider?
So in your PickupObject method, you're setting the cube's parent to be the hand, and resetting its rotation, which is good. The issue is you aren't setting the cubes position to be the same as the hand. It's moving with the player as a child should, but it's still offset from the hand.
Adding pickAbleObj.transform.position = handPlayer.position; should do it.
Though the cube may end up falling from the hand and onto the floor. If it does that, you'll need to shut off the Cube's rigidbody while its picked up, and turn it back on when you drop it.
also for DropObject you can do
pickAbleObj.transform.SetParent(null); instead of this
Turn off the cube's box collider and rigidbody when you pick it up, and turn them on again when you drop it.
pickAbleObj.GetComponent<Rigidbody>().enabled = false;```
And then set them to true in DropObject
Or you just move the hand gameobject a bit.
What's happening is the box is so close to the player its "pushing" them.
but the box can't move
so it just keeps pushing them back
I'm getting an error that says can not convert from "method group" to "string", how can I fix this?
i believe you replace Shoot with "Shoot"
ohhhHHH- thanks lol--
no problem
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 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.
That's a rough way to do it. Do Shoot() instead.
Mornin' all.
I'm trying something a bit different (for me at least), but having issues with my 'Ship' controller.
It's a very very very simple controller at the moment (basic forward back, no tweaking/lerping etc.), as you can see in the video I'm having a weird issue when I get to the poles of the moon. I'm not really sure why this is happening because in my head the ship should keep moving in the direction it's pointing, but it wigs out completely. Could anyone point me in the right direction please?
public class EagleController : MonoBehaviour
{
[Header("Scene Paremeters")]
[SerializeField] GameObject moonCenter;
[Header("Keybind Assignements")]
[SerializeField] KeyCode forwardKey = KeyCode.W;
[SerializeField] KeyCode backwardsKey = KeyCode.S;
[SerializeField] KeyCode turnLeftKey = KeyCode.A;
[SerializeField] KeyCode turnRightKey = KeyCode.D;
[Header("Eagle Physics Parameters")]
[SerializeField] float moveSpeed;
// Update is called once per frame
void Update()
{
// Always point at center of Moon
transform.LookAt(moonCenter.transform.position);
//MyInput();
if(Input.GetKey(forwardKey)) {
transform.Translate(Vector3.up * moveSpeed);
}
if (Input.GetKey(backwardsKey))
{
transform.Translate(-Vector3.up * moveSpeed);
}
}
}
Hello, I want to make something in Unity using coroutines.
I have a game project, where you should deliver "Pills" To your "Wife" because she is on timer.
I want the timer of "Wife" life to change when "Pills" are delivered to her by player.
Here's PlayerController code for this mechanic:
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("Pills"))
{
AudioSource.PlayOneShot(collect, 1f);
ice.SetActive(true);
hasPills = true;
Destroy(other.gameObject);
}
if (other.gameObject.CompareTag("Wife") && hasPills)
{
AudioSource.PlayOneShot(deliver, 1f);
hasPills = false;
gameManager.wifeTimer += 50;
ice.SetActive(false);
}
}
Here's GameManager script for "Wife" Timer:
public IEnumerator WifeCountDown()
{
yield return new WaitForSeconds(wifeTimer);
mainCamera.enabled = false;
gameOver.SetActive(true);
gameOverCam.enabled = true;
}
For some reason when I change the WifeTimer variable - Coroutine variable doesnt change and it still count downs that number that it was when the Coroutine started.
Also, I have an UI timer on screen that counts down the WifeTimer and that number changes when "Pills" are delivered, but Coroutine WifeTimer doesnt change
How can I update the timer of the Coroutine?
huh, I thought you needed StartCoroutine before a coroutins.. thanks :>
You do. I'm saying to do StartCouroutine(Shoot());
I think I'm right in thinking, that every time the timer changes, you'd need to stop the corouting (StopAllCoroutines(); ??) and then call the CoRoutine again and pass the new timer value to it.
Yeah, you're right
That was my first thought
But the thing is - I dont quite understand how does StopCoroutine works.
I cant use StopAllCoroutines cause there is another one running in GameManager
I'm not entirely sure if honest, I've never actually used it.
This may help.
https://docs.unity3d.com/ScriptReference/MonoBehaviour.StopCoroutine.html
I already checked that and did everything how it is there - but I guess since I call StopCoroutine in my PlayerController - It doesnt work in GameManager
I had this problem in my previous projects as well
StopCoroutine(GameManager.CoRoutine) ??
you can't change waitforseconds if it's currently sleeping. Use a basic timer loop and just do time comparison each frame.
if (other.gameObject.CompareTag("Wife") && hasPills)
{
AudioSource.PlayOneShot(deliver, 1f);
hasPills = false;
gameManager.wifeTimer += 50;
StopCoroutine(gameManager.WifeCountDown());
ice.SetActive(false);
}
Coroutine is still running
Can you maybe explain more? Please
public IEnumerator WifeCountDown()
{
while (wifeTimer > 0)
{
wifeTimer -= Time.deltaTime;
yield return null;
}
mainCamera.enabled = false;
gameOver.SetActive(true);
gameOverCam.enabled = true;
}```
private void wifeTimered()
{
if (hasTime)
{
if (wifeTimer > 0)
{
wifeTimer -= Time.deltaTime;
}
else
{
Debug.Log("Wife is dead");
wifeTimer = 0;
hasTime = false;
}
}
}
I already have that tho
It is in the UI timer
Will Yield Return change something?
how do you start the WifeCountDown?
In Start
Is the problem the coroutine is ending and you don't want it to even though you're changing the time?
show the line of code
void Start()
{
gameOverCam.enabled = false;
StartCoroutine(WifeCountDown());
StartCoroutine(gameCountDown());
Yeah, exactly
And if that's the case then what I said previously that you can't change WaitForSeconds if it's currently sleeping
ok so you need to cache the Coroutine passed back from StartCoroutine and use that in the StopCoroutine
I thiiiiiink this might have to do with transform.LookAt? You can see how the rotation of the ship is flipping between 0 and -180 each frame.
once it sleeps it aint waking till it waits it out
I think I have figured out one teeny issue, I was using vector3 instead of the ships Transform. But now I have a new issue I'm trying to figure out. lol.
But yeah, I think the LookAt is an issue too.
So when you cross the pole it flips the ship around to point back to the center, then crosses the pole, then flips the ship around to point back to the center etc etc.
LookAt uses the world space up as a default.
So maybe providing the ships transform.up would help instead?
Not sure, rotations are a weak point for me.
Yeah, trying a couple of different things. Thanks 🙂 And yeah, rotations always trip me up. lol.
But I definitely think it's related to how LookAt is rotating the whole ship when it passes the world up.
I have a timer manager for ya
What's that?
Then you only have to call add timer and give a delegate
Ah haaa, okay, yeah using the ships Transform.forward (cause of how it's rotated works like a charm. thanks for the idea :))
If you need help you can pm me
Looks like too much
According to the widget, it seems like there may still be some weird flipping, but doesn't seem to affect the actual game view.
I think that might be Unity just trying to align the widget in a way where you can best see it?
Idk the ship aint flipping and the inspector says we're good.
So fuck it.
We ship it.
Yeah that's what I thought. lol.
Now to deal with the headache that is lerping and rotating left/right. lol.
Any idea how can I stop it instead?
I will say that in the future, you might need to do something a bit more specific to clamp the ship to a specific height from the planet.
A low FPS/high velocity with your current set up can send the ship to bum fuck no where.
StopCoroutine or use the code I provided and set the timer to 0
Yeah, the ship will be moving pretty slowly, it's just this fast atm so I'm not waiting for days to test. lol.
Cause your IDE is not configured
how do i configure it?
!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
• Other/None
i think you forgot to use Capitalisation when you were doing Rigidbody2D rb; and rb = getComponent<Rigidbody2D>();
ill try that, tahank you
the correct spelling should be
Rigidbody2D
and GetComponent
Which he would know if he had his IDE configured
idk what IDE is 
is it like visual studio plugins
that come with unity
Okay, now I'm really confused. I've got this exact piece of code in another project and it works great, but on this new project my ship is just 'bouncing' back and forth (always trying to get back to 0, and I can't see why.
if (Input.GetKey(turnLeftKey))
{
transform.Rotate(transform.forward * -turnLeftSpeed * Time.deltaTime);
}
What
Visual Studio is the IDE
idk
i changed it over and its still saying it cant be find. i also configured it
IDE stands for integrated development environment. Visual Studio is a type of IDE, ya. They're just the programs that let you edit/run code.
Visual Studio needs to be configured to recognize Unity.
ok
thanks
Hey, good morning. I want to make a Game about balls falling down and everytime the ball hits a obstacle is should be counted and should get saved in a Variable in the ballprefab. At the End of the parkour the Value should get addet to another script like a moneysystem, which i already have. But if I spawn multiple balls the value gets overwritten? Can someone explain how i can solve this problem?
I then send the value to another script via an instance
what values got overwritten?
Well each time you spawn a ball with this OnContact script, it sets itself as the value in that instance variable.
And the Value in the new OnContact starts at 1.
Thus, it gets "reset".
Those other OnContacts still exist, but they're no longer what that Instance variable is pointing to.
Perhaps what you want is a static Value, not a static Instance.
Okay, i understand, but how do i count then the conntacts, if there are more than one ball
For a simple solution, just make Value static.
or store the variable in other singleton
Would definitely be better if this was in a dedicated Manager class, but ya.
Ok thank you, i will try it
Anybody have any clue please?
This should make it roll/rotate along its own Z axis. What other components does it have?
Tell me a story about initialising components, daddy...
I have a component attached to a game object, but the fields in that component remain null
How do you initialize the fields?
Like how do you define them or how do you assign a value to them
Does anyone have an utility method (or could tell me how) to convert a Color to an HDR color at runtime providing an intensity? leaning towards Color Mutator
https://youtu.be/HRLdcMil7Ec?si=MWDMu3UW7BEWlO8M
as an aside
@verbal dome so far I've initialised them with the standard 'x = new ({class} (class field))', but that's still returning null
Download the source code: https://www.patreon.com/posts/source-code-for-88052099
We've all been there: You design a slick C# method, but then it might need to return... null. How many times have you crafted a method, sometimes a complex one, only to encounter the inevitable predicament of possibly returning null?
The ripples from this single dec...
I get the impression that I'm missing a lot
I had a semi-functional house-of-cards last week XD
to destroy a gameobject (monster) is it better to check the health on the Update() or is it better to do it when doing the damage calculation?
Better show us your code
the offending code:
public Feature Ambition { get; set; }
public Feature Vitality { get; set; }
public Feature Nous { get; set; }
public Feature Mystique { get; set; }
public Feature Might { get; set; }
public Feature Grace { get; set; }
public Feature Humour { get; set; }
public Feature Habit { get; set; }
public Representative()
{
Ambition = new Feature(FeatureTitle.Ambition);
Vitality = new Feature(FeatureTitle.Vitality);
Nous = new Feature(FeatureTitle.Nous);
Mystique = new Feature(FeatureTitle.Mystique);
Might = new Feature(FeatureTitle.Might);
Grace = new Feature(FeatureTitle.Grace);
Humour = new Feature(FeatureTitle.Humour);
Habit = new Feature(FeatureTitle.Habit);
// Assign the initialized features to the provided _features array
features = new Feature[8];
features[0] = Ambition;
features[1] = Vitality;
features[2] = Nous;
features[3] = Mystique;
features[4] = Might;
features[5] = Grace;
features[6] = Humour;
features[7] = Habit;
}
oops - I hate when that happens
the get & set properties are getting references in the editor, but the Representative constructor got nothing
Is this a MonoBehaviour?
yeah
You should not use constructors with MonoBehaviours (or other UnityEngine.Objects).
Use Awake and/or Start for initialization instead
Also you could can use an initializer with a property: public Feature Ambition { get; set; } = new Feature(FeatureTitle.Ambition);
thanky
Also unity C# version doesn't support nullable ref types as far as I know. So this video is not relevant
my bad - it looked interesting to my learning
So I have theses 2 methods in a Utility
public static Color PercentageToColor(float percentage, Color minColor, Color maxColor) {
return Color.Lerp(minColor, maxColor, percentage);
}
public static Vector4 ConvertToHDR2(Color color, float intensity) {
return color * Mathf.Pow(2,intensity);
}
And I call them in an update like this, goal is to change a material's emission color over time
private void Update() {
var percentageAsColor = ColorsUtility.PercentageToColor(
GetComponentInParent<TowerController>().GetMaintenanceLevel(),
GameTheme.positiveColor,
GameTheme.negativeColor
);
_material.SetVector(
EmissionColor,
ColorsUtility.ConvertToHDR2(percentageAsColor, 4f)
);
}```
Issue is that although the intensity is always set to somewhere around 4f, it's not exactly 4f as it would be setting it in inspector. and also the intensity value goes down over time. noticed it start at 4.7f and ended up at 3.9f, any idea what's wrong or the proper way to do this?
hello, can i recieve help from guys who now unity2D on this server, because i have a small problem and am new to the dev game
With the assumption that negative color and positive color are not changing, the resulting color from percentage should be somewhere between the two colors. The intensity parameter according to your code (hard coded) would be exactly 4f. I'm not sure what you're referring to with the varying values 4.7f and 3.9f.
The solution is not to ask to ask, but just to ask. Someone who is idling on the channel and only every now and then glances what's going on is unlikely to answer to your "asking to ask" question, but your actual problem description may pique their interest and get them to answer.
This is the beginner coding channel. If it's related to coding, you should ask here else try #💻┃unity-talk
can someone help me with a tiemr? so i want to make a 3 hit based combo and im assuming the main premise of it is that
if hit 1 is 1f and press "fire1" then play anim for hit 2
but i dont know how to make it a timer. the timer would preferably be like 2 secconds for each hit and if the button doesn't get pressed its back to idle position.
here is my relevant code so far:
`public void attack()
{
if (Input.GetButtonDown("Fire1")&& IsGrounded())
{
hugo.GetComponent<Animator>().Play("HguoFire1");
attacking = 1f;
}
}`
Probably something like this (relative to your code)cs public void Attack() { limit += Time.deltaTime; if (limit > 2f) attackType = 0; if (!Input.GetButtonDown("Fire1") || !IsGrounded()) return; hugoAnimator.Play(hugoCombos[attackType]); limit = 0f; attackType++; }
limit is a float i know that but how do i add attack type and what does the ++ mean
Attack type would be an integer to access the wanted attack string from an array or list. The ++ would be post increment - short hand for attackType += 1.
how do you test for Ground?
Screen.SetResolution(resolution.width, resolution.height, Screen.fullScreenMode == FullScreenMode.FullScreenWindow); Debug.Log($"resolution height {Screen.currentResolution.height} and width {Screen.currentResolution.width}");
this is my code to change resultion but it's not working in build or editor always debug same resultion
maybe make your Box not Ground but add a Plane to the top of the Box which is Ground
I can only supply answers to the questions asked, I'm not a mind reader
of course there is, but are you ready for such complexities?
so you write your own collision code and use the normal of the contact to decide what to do about it
can someone help? basically i have a timer for this system im doing and im trying to make it so when i let go of the fire button the float goes to 0f slowly from when poressing it 5f.
here is the relevant code
`public void Attack()
{
if (Input.GetButtonDown("Fire1") && IsGrounded())
{
attacking = 5f;
hugo.GetComponent<Animator>().Play("HguoFire1");
}
if (Input.GetButtonUp("Fire1") && IsGrounded())
{
attacking -= Time.deltaTime;
}
}`
that code makes no sense. your if statements will only fire once
Sorry was afk having lunch. And Yeah, that's the idea (the rotational thing), but it's like it's fighting to get back to 0 all the time.
Ship has a box collider and a rigid body. It's a little odd.
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 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.
public class EagleController : MonoBehaviour
{
[Header("Scene Paremeters")]
[SerializeField] GameObject moonCenter;
[Header("Keybind Assignements")]
[SerializeField] KeyCode forwardKey = KeyCode.W;
[SerializeField] KeyCode backwardsKey = KeyCode.S;
[SerializeField] KeyCode turnLeftKey = KeyCode.A;
[SerializeField] KeyCode turnRightKey = KeyCode.D;
[Header("Eagle Physics Parameters")]
[SerializeField] float moveForwardSpeed;
[SerializeField] float moveBackwardSpeed;
[SerializeField] float turnLeftSpeed;
// Update is called once per frame
void Update()
{
transform.LookAt(moonCenter.transform.position, transform.forward);
//MyInput();
if (Input.GetKey(forwardKey)) {
transform.Translate(Vector3.up * moveForwardSpeed);
}
if (Input.GetKey(backwardsKey))
{
transform.Translate(-Vector3.up * moveBackwardSpeed);
}
if (Input.GetKey(turnLeftKey))
{
transform.Rotate(transform.forward * -turnLeftSpeed * Time.deltaTime);
}
if (Input.GetKey(turnRightKey))
{
}
}
}
Full code, just in case I'm missing something really obvious (and yes I know it stupidly simple etc. lol)
Please use the 'Large Block' option for code longer than a few lines
My bad, never really sure what the 'cutoff' is for large/small blocks.
You should not move move a rigidbody with transform
basically, imo, anything less than 10 lines is ok for inline, more than that should be in a paste site
Okay cool. Will use that guildline from now on 🙂
Well tbh, the rigidbody is only on there so that I can have collisions. lol.
where do you see a Rigidbody in that?
Right, and moving via transform will not detect collisions reliably and you get all kinda weirdness
They said it in an earlier message
Ok, I'm missing context, mb. Yes, do not mix transform and Rigidbody manipulation
I'm only using the collision to detect when the ship has landed and trigger an animation. @languid spire there is a rididbody on the ship. I'm just not using it for movement
does not matter, if you have a Rigidbody you MUST use it for movement and Rotation
Okay.
Why?
because otherwise they will fight and screw up
Moving via transform will not really notify the physics system and make it detect collisions
His RB could be kinematic. PhysX will sync with transforms at the beginning of the first physic step for the frame
kinematic is different, but afaik, that is not the case here
I am looking for a UI feature which I know exists but forgot how to implement:
- I have 2 UI elements (say a Character and a Square)
- The square limits how much I can see of the Character - outside of the Square, the Character is invisible
- When the square gets bigger, I can see more of the underlying Character
Can someone help out?
Image Mask
thanks!
or Sprite Mask
Sprite Mask for WorldSpace right?
yes
99% not a unity issue
My animator is not playing the default "Flying" animation please help I am getting it using GetComponent<Animator>() in Start() of my character script but it's still not working I am also calling animator.play("Flying") i get no errors and no null exception but the animation just does not play.
the name of the idle state in animator is correct
Could be wrong, but you animation speed is set to 0 (top left of your first image)
omfg i feel so dumb
Nah, easy to overlook, especially if you've been looking at it for a while.
i had set it to 0 cause i thought it was for sample rate at first but then i found it and never switched it to 1
Thank you! <3
No probs. 🙂
Okay, so I've re-written my controller, but am now stuck on something. lol.
Originally I had the ship always pointing to the center of the moon using LookAt. But now that doesn't work (because, physics. lol.). And I'm a little stuck on how to keep the ship perpendicular to the surface of the moon and maintaining the same height (I don't need/want to move the ship 'up and down).
Would anyone have any ideas? ((Image for Illustration))
Hello, small question regarding AI and triggering their behavior. If I want to detect if an AI needs to shoot at a player, is it better to use colliders or to check the distance in an update method? Which one more performant if I'll end up have dozens of such AI in the map?
I've checked several tutorials and their code varies. Sometimes it's a collider, sometimes it's an update. Not sure which one is better at the moment
One idea is that you could use a joint that has the look rotation as the target rotation. You can get a rotation similiar to LookAt with Quaternion.LookRotation
Collider will always be more performant than a RayCast in Update
ConfigurableJoint can do that at least @ruby python
Or you can manually add torque to rotate towards the desired rotation, but I think thats more complex
Okay, thanks. Time for some reading. Never used joints.
Hello i have a problem in my thingg ;-;
I cant assign the AR session game object to the raycastmanager
I did copy paste the exact script too
Does it have the correct component on it?
ARRaycastManager
It wouldn't be a raycast. It's a simple math function to check if the distance between the ai and the player is less than 10 meters for example. No raycast needed.
Vector3 playerDirection = agent.target.transform.position - agent.transform.position; if (playerDirection.sqrMagnitude > agent.config.initChaseDistance * agent.config.initChaseDistance)
Well you dont have the component that you are trying to drag in 🤷♂️
Collider would still be more performant I think as the distance calculation is always running on every frame.
it dosent have the ARRaycastManager tho
Got it. Yes it would run on every frame indeed. I'll go with colliders. Thanks a lot!

