#💻┃code-beginner
1 messages · Page 829 of 1
☠️
if you change it back, do you get the same issue?
if not, then maybe https://shouldiblamecaching.com
Yes, changing it back breaks it again
Caching was actually what the first guy thought, so I regenerated my library file and that didn't fix it
i'd guess something's messing with that specific name then. i don't think it'd be unity itself though
that's definitely out of my expertise though
if you want to debug further yourself i guess you'd test it in different files next
shot in the dark basketball would be to double check that there isn't any antivirus stuff going on or installing the project in a onedrive folder or something
I've just got windows defender (which shows no recent activity) and the project is installed in my user folder. I think this seems like an uncommon enough bug that I'll just begrudgingly change the beautifully crafted name of my variable and move on with my day lmao. Thanks for your help guys ❤️
Here is my movement code, when using a controller slightly moving the left stick in any direction should result in slower movement and pushing it fully should result in full speed. How can I achieve this? I remember having this exact same code a few months ago in a different project and it would work but not anymore for some reason.
{
Vector2 input = Vector2.ClampMagnitude(currentInput, 1f);
Vector3 camForward = myCam.transform.forward;
Vector3 camRight = myCam.transform.right;
camForward.y = 0f;
camRight.y = 0f;
moveDirection = (camForward.normalized * input.y + camRight.normalized * input.x).normalized;
float currentSpeed = isGrounded ? moveSpeed : airSpeed;
rb.AddForce(moveDirection * currentSpeed, ForceMode.Acceleration);
}
You're normalizing your moveDirection, which means if input is less than 1, it'll become 1
So, you're always moving at moveSpeed or airSpeed
You might want to consider ClampMagnitude like you did for the input itself instead of normalizing it
Thanks! got it working perfectly now
I am trying to make a game where the GameObject doesn't fall off the plane using vector3. I've done it this way and it works but depending on my fps the barrier isn't exact. Is there be a better way of doing this?
(Red highlight is the barrier and movement code)
Video for reference:
!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.
clamp the position instead of just saying "translate or don't translate"
instead of "stop moving once you're past this point", think of it as "move only to this point", ie limit the final position
using physics to handle that logic could also be a choice
yep using physics and having colliders there is another option
I'll look into clamp, is it just a better way of moving an object?
Oh alright, that would be extremely useful
the idea is:
instead of condionally translating, just always translate. Then find the clamped position and move the object there
e.g.
transform.Translate(Direction * movementSpeed * Time.deltaTime);
Vector3 clampedPos = transform.position;
clampedPos.x = Mathf.Clamp(currentPos.x, leftBound, rightBound);
transform.position = clampedPos;```
you could also add to the current position directly rather than going through transform, that's also an option
Basically yes it's Unity's version of https://learn.microsoft.com/en-us/dotnet/api/system.math?view=net-10.0 that works with floats instead of doubles
so you wouldn't have to juggle it through the transform and back
most of it just delegates to System.Math anyways lol, but there are a few differences, like how Sign(0) works
guys, i am losing my mind here
i have things plugged to my pc that is affecting my getaxis, but even when unplugged unity is still acting like they exist, or i have something that is affecting it
how do i remove all other input apart from keyboard/mouse from my project
check the input debugger
this sounds a bit like an xy problem
the input debugger i'm referring to is for input system
is it just that they're keeping the same value as when you unplugged them?
seems like a pretty generic issue, could google about that probably
i dont wanna restart, i have alot of things open and dunno what i'll lose if ill restart
i figured there'd be an input option in the settings or something
i saw a for loop too of like just looping through the devices and disabling everything apart from kb+m
save.
but thats hacky and i dont wanna do it
unity is kinda aids tbh i have more luck designing my own engine in C
nobody's forcing you to use unity
are u good bro
are you?
i am, this guys just useless, being super condescending and giving absolutely no help
like why even type
what is this lol
this is a single solution for a single device
you havent given us much info to go off of
plus you refuse to restart your pc for some reason
okay with all due respect
what are you expecting us to do here for you
i would like someone whos had this issue to help me
you clearly don't know
and thats okay
but going back and forth isnt solving anything
the dude in the forum seems to have had the issue. there's a lot more people on the internet than on this server, hence why i recommended it
most people here would be using inputsystem anyways lol
that's besides the point though
this is litterally how things get solved
nobody is going to show up here with a singular magic solution
not without you giving us more information and context
all im asking is "where is the settings to enable/disable input devices"
this is all i need to know
no back and forth needed for this answer
are they even exposed for the old system
wym
if you're seeing code involving InputDevices, that's for the new system
i will get to the new input system at some point im sure, but surely theres a setting in the project settings to enable/disable input devices
neither the Input api docs nor the Input Manager manual reference any method to reference input devices directly
there is the ResetInputAxes that was mentioned in the forum i linked you. could give that a shot
ill try it but it seems even in the thread it doesnt work for him
seems it resets it for 1 frame
nvm it doesnt allow for any movement now
like yeah my entity is no longer moving, but now it cannot move at all
Tbh this is why they made the new input system to begin with lol
solve headaches like this and makes the entire thing streamlined
make sure you arent' resetting it every frame
but yeah before the new input system was a thing i heard a lot about wrapping the old input manager anyways
ggs i have a headache im done for today ty anyway
hey i got an issue with 2d top down mechanics. I got a script where I can move the character right, left, up and down. but if I press W and S or A and D at the same time, the movement cancels eachother out (-1 + 1 = 0) is there a common fix for that? heres the script if it helps ```using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerMovement : MonoBehaviour
{
GameControls input;
public float walkSpeed = 5f;
private Rigidbody2D rb;
private Vector2 moveValue;
private void Awake()
{
input = new GameControls();
rb = GetComponent<Rigidbody2D>();
}
public void Update()
{
moveValue = input.Player.Move.ReadValue<Vector2>();
}
private void FixedUpdate()
{
// Physics movement
rb.linearVelocity = moveValue.normalized * walkSpeed;
}
private void OnEnable()
{
input.Player.Enable();
}
private void OnDisable()
{
input.Player.Disable();
}
}```
What do you want to happen instead?
the last input pressed should be used, so if i move right and press left, theres a reason, so the player should move left and not just stand stil
wowie player movement
is this 3d?
2d top down like the old zelda games
oh
you should switch from polling ReadValue to using the input action performed and canceled event callbacks
you keep manual track of the button presses and store the latest one
im still new so I dont know what that is 😄 polling? callbacks?
"polling" is continuously requesting the state, like you're doing here
gimme a sec
a callback would be registering an action for the inputsystem to call when something happens (in this case, when the input value changes)
// add a direction to a list when you press a key, remove on release
input.Player.Move.performed += ctx => moveStack.Add(ctx.ReadValue<Vector2>());
input.Player.Move.canceled += ctx => moveStack.Remove(ctx.ReadValue<Vector2>());
// you then move towards the very last item added to that list
Vector2 moveDir = moveStack.Count > 0 ? moveStack[^1] : Vector2.zero;
i stole this from a forum post but it illustrates it nicely
Here 👆
is ctx a thing or is it something you just named yourself? also dont know what += and => does (:
ctx stands for context
its generally used for objects that provide some kind of methods to pass data or trigger actions
here we use to contain the vector2 value from the input actions
Is there an actual difference? It does the same: storing the read Vector2 value in a variable. Or do I miss something?
youre close but not really lol
same general concept but we arent using ctx to just store the vector2 value
ctx is an object
it can contain more information than just the vector2 value
{
if (isOpen)
{
t += Time.deltaTime * rotateSpeed;
t = Mathf.Clamp01(t);
transform.rotation = Quaternion.Slerp(closeRot, openRot, t);
}
else
{
t += Time.deltaTime * rotateSpeed;
t = Mathf.Clamp01(t);
transform.rotation = Quaternion.Slerp(openRot, closeRot, t);
}
}```
I've got this door script, I believe it should work but for some reason it has been glitching out. When I change the bool it waits a bit and only when t = 1 does it go to the rotation. the slerping is not happening. openRot and closeRot btw are both quaternions and t is just a float and I can see its actually going from 0-1 properly.
My brain does the windows error sound when i see += . does it mean that t stores Time.deltaTime * rotateSpeed in addition to whats already assigned to t? also isnt "t = Mathf.Clamp01(t);" just overwriting t to thatever Mathf.Clamp01 means?
Try printing t or inspecting it in the debugger and see if it's what you expect
both of these seem correct to me
In the inspector t is working as expected
I made it a custom variable
can you show the full script?
What sets isOpen? Is it maybe being toggled rapidly, like if it were toggled in an OnTriggerStay or something like that?
Likewise, when does t reset to 0?
no += is subscribing to the event lol
in this case it's just a simple x = x + y written as x += y
this
oh sorry
i thought this was what nuke was refering to
I'll send it soon. But I just have an open door function which changes the bool and sets t to 0 and checks if it's locked and a function for opening a locked door
He seems to be talking about t += Time.deltaTime * rotateSpeed;
to be fair he did ask about the other one too 🧐
I could also send the code for how the openDoor is called
!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.
please use the paste sites for larger blocks of code
sorry
a powerful website for storing and sharing text and code snippets. completely free and open source.
Hey, I am very confused with how I should update this:
return Object.FindObjectsByType<T>(FindObjectsInactive.Include, FindObjectsSortMode.None);
I keep getting a warning in Untiy 6.5:
/home/nn/Data/Projects/Unity/Katana/Modules/UnityUIEffect/Packages/src/Runtime/Internal/Utilities/Misc.cs(24,77): warning CS0618: 'FindObjectsSortMode' is obsolete: 'FindObjectsSortMode has been deprecated. Use the FindObjectsByType overloads that do not take a FindObjectsSortMode parameter.'
And the wiki doesn't really offer an alternative for sorting, so what do I do?
https://docs.unity3d.com/6000.5/Documentation/ScriptReference/Object.FindObjectsByType.html
Use this return Object.FindObjectsByType<T>(FindObjectsInactive.Include);
so sort mode none is the default behavior now?
I guess? This is a new deprecation - and a surprising one to me
Haven't run into it personally, but they only recently introduced that stuff so it's surprising they're deprecating it
So, it's not doing anything until it hits 1.0 then suddenly snaps into position, am I understanding this issue correctly?
Just as a sanity check, I'd say change the contents of those conditions to just transform.rotation = openRot and the same for closeRot. Does it snap into the orientations you expect instantaneously?
yes
Hello I need help with making my isometric tile palette fit in its diamond shape
Hello I need help with making my isometric tile palette fit in its diamond shape
Im not sure why it does this ive been stuck on this for a while, i've followed official docs and i just cant seem to get itright
Im thinking maybe its caused by the actual sprite img sizes?
this is a coding channel
most likely issue with PPU
I moved the slerp to a variable and debug.log it and the quaternion is indeed changing
and if I try to adjust in the inspector the rotation it does not let me
Okay, now put the slerps back, but hard-code in t as 1 instead. Does it do the same thing?
changing from slerp to lerp gave this error
Assertion failed on expression: '!CompareApproximately(aScalar, 0.0F)'
UnityEngine.Quaternion:Internal_Lerp (UnityEngine.Quaternion&,UnityEngine.Quaternion&,single)
Door:Update () (at Assets/Door.cs:52)
yes
it does the smae thing
That would imply that at least one of your Quaternions is malformed. How are you setting openRot and closeRot?
they're quaternions in the inspector I had to input the values as euler though
so openRot is 0, 0, 0 and closeRot is 0, 90, 0
why are they quaternions in inspector ?
So, at some point along the slerp, it's making a malformed Quaternion?
It might be easier to see if you make openRot and closeRot explicitly into Vector3s, then do Quaternion.Euler(openRot) and such instead? That way it might at least tell you what the problem child is
so I could have variations of the rotation
I just checked, making a serialized Quaternion gives you a Vector3 input in the inspector
oh huh thats interesting
Yeah, I didn't know that either. I had to go check.
It might be doing something fucky under the hood though, so I think explicitly setting euler angles and converting them later might help?
I bet your openRot is malformed
Set it to some other value, then set it back to zero
Do not hit undo
The default value for a Quaternion is all-zeroes (because it's a struct)
nope
so, if you don't touch the field in the inspector, the actual quaternion value is [0, 0, 0, 0]
I even reset the script
resetting the component will not help
I set all the values to a random number and then swtched back to 0
To avoid this, give the fields default values of Quaternion.identity
Btw I'm trying the vector3 approach digiholic suggested
can anyone explain input.Player.Move.performed += ctx => moveStack.Add(ctx.ReadValue<Vector2>()); because im totally lost here to understand what += is (and the fact that its a subscription is not helping me) what is it subscribing to? what is ctx, a value, a variable? and the rest of the block is also not making sence. I tried let chatGPT explain it to me but even the explainations there are too hard for me to understand.
You can split this into two lines to make it a bit easier to grok
=> is used to declare an anonymous function
it's like a method (e.g. Awake, Update, etc.), except that it doesn't have a name
it's just an object
ctx => ...
This is an anonymous function that accepts one argument.
The argument is named ctx
you could rewrite this at:
private void HandleMove(InputAction.CallbackContext ctx) {
moveStack.Add(ctx.ReadValue<Vector2>());
}
void Start() {
input.Player.Move.performed += HandleMove;
}
In fact, you should probably do this!
You can never un-subscribe from the performed event if you use an anonymous function like that
you need to un-subscribe with the exact object you subscribed with
bleh anonymous functions, they always feel so dirty to use
btw they named itctxbut can be anything you chose, its just here short for context
as long as you did this without undoing, it should work fine – I just tried it out myself
the last one had the values changed
They're fine when you're doing something like a Linq query where they're just gonna disappear, but for subscribing you shouldn't use em, so you can remove em later
i'm slerping from a quaternion to Quaternion.identity
I use static anonymous functions along with RefLinq quite a bit
static forbids you from capturing anything, which causes an allocation
Move.performed is an event. The event will be invoked or fired whenever you touch your joystick. The += thing here says "whenever the performed event is invoked, please run this function on the right". So - whenever the joystick moves, it will run: ctx => moveStack.Add(ctx.ReadValue<Vector2>());
ah, right, i forgot about that half 😉
WHich is just a shortand way of writing a function
ctx => moveStack.Add(ctx.ReadValue<Vector2>()); is shorthand for:
void MyFunction(CallbackContext ctx) {{
moveStack.Add(ctx.ReadValue<Vector2>());
}```
So that function will run whenever you move your joystick after you do the += thing
long winded / docs as well. the rabbit hole goes deep
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/lambda-expressions
I use them whenever I need to do a certain thing once
meaning that there is no sense in writing a reusable method
thank you, you made is so much easier to understand! why are documentations always explained in such a technical way if it could be explained as simple as that
notably, you can also turn a method into an object that you can pass around
and thehttps://paste.myst.rs/wkx6hgt1 this is the code I have with the vector 3 instead
a powerful website for storing and sharing text and code snippets. completely free and open source.
void Hello() {
Debug.Log("Hello");
}
System.Action foo = () => Debug.Log("Hello");
System.Action bar = Hello;
note that you've switched to the Unity Mathematics quaternion type here
You probably just meant to do Quaternion.Euler
even euler did the same thing
they want to cover all bases, plus people who created / wrote those are generally on some 4D mental plane lol
some doc pages are getting better though and feel less "robotic" it used to be bad
and whenever I use quaternion it does the snap issue
so, if you turn on isOpen in the inspector, the door doesn't move at all until it gets to t=1?
well in the new code with the vector3 it goes to the rotation and overshoots
and other values get it completely wrong
you're setting transform.rotation, rather than transform.localRotation, which is suspicious to me
this means that you're setting your world-space rotation, rather than your rotation relative to your parent
that wouldn't cause the snapping
but it would cause the door to appear to rotate in nonsensical ways
It is in the world space the door
Like the door script is on an object with no parents
Should I make it local rotation
I'd have to try tmrw thougj
It's weird cos this is the same way I've always done doors and rotations
It is weird, yes. Everything you're doing looks fine to me
At this point, I would try making a new door (well, just a cube with the Door component on it) and seeing if it behaves right
i don't have full context, but just a quick check - have you checked for animators (or other components) on that object, that might be controlling the transform?
That's my thought, yeah
external interference!
It'd also be helpful to see a recording of what's happening
If the door is eventually rotating, then I doubt something else is controlling it
(this kind of thing is usually all-or-nothing)
Hello, so I am trying to figure out the simplest of concepts (animator transitions) but I am struggling way too much.
How my system works is simple, I use an animator manager that plays an animation with CrossFade() and jumps to the specific animator states (in this case Block Hit and Block Start) and then they transition all the way to an Empty state which just has a script that resets some combat flags.
The input for blocking (which is RMB) is directly controlling the animator bool flag isBlocking (so it is unrelated to the combat manager isBlocking flag).
My issue is that for some reason my Block Hit animator state and Block Loop do not want to cooperate. The bug happens when i block a hit and then stop blocking immediately after, which causes the Block Hit state to be playing even after transition and Block Loop does not exit through the transition to Block End even when the condition is met and has no Exit Time.
Can someone explain what is happening because this makes 0 sense to me?
Ye it did not have any animations. I'm still prototyping the game and it was just a cube I'll try making a new door tho
by that, do you mean it has an animator/animation but no states/clips, or no animator/animation component
idunno this is animator problem or most likely coding problem. i have short weapon fire animation which length is 1 second. in game its looping for... 2-3 seconds?
here is my code and video
public void HandleShoot()
{
muzzleFlash.Play();
currentAmmo--;
Debug.Log(gunData.weaponName + currentAmmo + "/" + gunData.magSize);
gunAnims.SetBool("Fire1", true);
Shoot();
Invoke(nameof(PlayFireAnim), 1f);controller.ApplyRecoilCam(gunData); } //shit i need to make timer without courutine cuz i think it will break my code void PlayFireAnim() { gunAnims.SetBool("Fire1", false); }
This still makes no sense to me but I've realized that setting crossfade duration to 0.07 or more (number is probably related to the transition duration) for that specific animation breaks the transitions.
Setting a value below that fixes the problem and makes the animations transition smoothly with no hiccups.
You can look at the Animator with the animated object selected, in Play mode, to see what is actually happening with it (see Nuumi's video above for example)
Really looks like you should use a Trigger param instead of a Bool param here
A trigger is just a bool that turns to false immediately when it is "used"
OH for real, thank you
Also FYI the animation you are showing is 0.1 seconds, not 1 second
That's why it plays multiple times in one second while the bool is true
But yeah use trigger
i didn't sleep this night and i started learning animator stuff hehe
Make sure to remove the condition in the transition from fire->idle so it happens automatically
(If it already doesn't get removed when you change to trigger)
Are you depending on animation events for some transitions?
Because they might not fire always when a fade is happening, IIRC
I do have a custom animation event system which handles that with no issue, but my problem is with the transitions from Block Hit to Block Loop.
I've tested it without the events and it still does the same thing. What solved it was making the crossfade duration lower than the duration of the transition from Block Hit to Block Loop.
can someone tell me why using this.gameObject in the script gives the error "object reference not set to an instance of an object". when i look at the script, "this" is slightly dimmed out, making me think that its the problem. i have it in fixedUpdate
Show the full code and the full error message including the stack trace
"this" is slightly dimmed out, making me think that its the problem
That's definitely not the problem. It's dimmed out hbecause it's unnecessary
you could have just written gameObject instead of this.gameObject
public class PlayerController : MonoBehaviour
{
private GameObject player;
player = gameObject;
void FixedUpdate()
{
if (isDrowning == true)
{
Movement(false, false);
isDrowning = false;
PlayAnimation.Drown(player); //error here
}
}
That is PlayAnimation.Drown(player); not this.gameObject causing the error
Does this code even compile?
None of this should compile
player = gameObject; should be an error because you can't access non static variables outside a method
and:
PlayAnimation.Drown(player); //error here you're using a variable that doesn't exist here called PlayAnimation
This looks like this is not the full code
ok my bad give me one sec to show you what i had because i accidently removed 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.
yes its my bad....
im sending
{
private Animator animator;
public bool isDrowning = false;
public bool allowedToMove = true; //only for movement
public bool allowedToControl = true; //for movement and everything else like item usage
private AnimationPlayer PlayAnimation;
public GameObject player;
void Start()
{
spriteRenderer = GetComponent<SpriteRenderer>();
animator = GetComponent<Animator>();
}
void Update()
{
}
void FixedUpdate()
{
currentPosition = transform.position;
movementDirection = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"));
if (allowedToMove == true)
{
transform.position = new Vector2(currentPosition.x + movementSpeed * Time.fixedDeltaTime * movementDirection.x, currentPosition.y + movementSpeed * Time.fixedDeltaTime * movementDirection.y);
}
if (isDrowning == true) //when we impliment water detection, just put this there
{
Movement(false, false);
isDrowning = false;
PlayAnimation.Drown(gameObject); //error here -----------------
}
animator.SetFloat("horizontalInput", movementDirection.x);
animator.SetFloat("verticalInput", movementDirection.y);
if (animator.GetCurrentAnimatorStateInfo(0).IsName("RunRight") || animator.GetCurrentAnimatorStateInfo(0).IsName("IdleRight")) //only until we get right facing animation
{
spriteRenderer.flipX = true;
}
else
{
spriteRenderer.flipX = false;
}
}
void DrowningAnimationFinished()
{
PlayAnimation.RespawnAnimation(gameObject);
}
public void Movement(bool allowMove, bool allowControl)
{
allowedToMove = allowMove == true ? true : false;
allowedToControl = allowControl == true ? true : false;
}
}
Ok and which line is indicated in the error message?
i removed some variables outside of the problem because of character limits here
AnimationPlayer.cs
public class AnimationPlayer
{
void Start()
{
}
void Update()
{
}
public void Drown(GameObject player)
{
Animator animator = player.GetComponent<Animator>();
animator.Play("Drown");
}
void Push()
{
}
public IEnumerator RespawnAnimation(GameObject player)
{
SpriteRenderer spriteRenderer = player.GetComponent<SpriteRenderer>();
float drowningDelay = 0.75f;
spriteRenderer.color = Color.clear;
yield return new WaitForSeconds(drowningDelay);
spriteRenderer.color = Color.white;
player.GetComponent<PlayerController>().Movement(true, true);
}
}
i just marked it
im sorry guys im new to this so mb for being difficult
PlayAnimation.Drown(gameObject);
Then PlayAnimation is null
oh
You never assigned it
and it's private so it's certainly not being assigned in the inspector
do i have to do PlayAnimation name = new PlayAnimation();
No, it's a MonoBehaviour
you need to assign it to the actual one you want to reference
make it public and assign it in the inspector - that's the simplest way
im sorry i dont really understand.
i put this
public AnimationPlayer PlayAnimation;
set it to public but it doesnt show in inspector
if its not obv im a beginner so im a lil lost
Do you have compiler errors? Check the console in unity (clear it first)
Oh, and importantly, AnimationPlayer needs the [Serializable] attribute
er
Otherwise it won't be shown in the inspector (or saved)
it's confusing because that script has Start and Update but it's not a MonoBehaviour
so it's not clear to me if this is supposed to be a MonoBeahviour or not
Yeah, maybe they made it with thet mono template and removed : MonoBehaviour...?
I actually assumed it was above when I said not to use new()
if it's supposed to be a plain C# object then yes you can use new() to instantiate it
this is the only error i get when i turn on isDrowning in the inpspector
but I would remove Update and Start from it to avoid confusion
just removed them
@hot hamlet ^
well either that - or you create it manually with new()
[Serializable] public AnimationPlayer PlayAnimation;
Attribute is not valid on this declaration type. It is only valid on specific declarations. (the [Serializable] has the red line]
it would go on the class definition, not on this field
Is AnimationPlayer something you want to edit in the inspector?'
there doesn't seem to be anything on it to edit
it's just a couple of public methods
it would definetly be convinient later on lol
if you want to make the animation values configurable it might makje sense
[Serializable]
public class AnimationPlayer
this worked 
and i think i understand why
so i appreciate all the help
Hey, I am porting some older code to unity 6.5, and can't figure out whether I should explicitly use the ToULong, or whether the implicit ToString already does that in the background?
https://docs.unity3d.com/6000.5/Documentation/ScriptReference/EntityId.ToString.html
#if UNITY_6000_5_OR_NEWER
_foldouts[group.Key] = new SavedBool($"{EntityId.ToULong(target.GetEntityId())}.{group.Key}", false);
#else
_foldouts[group.Key] = new SavedBool($"{target.GetInstanceID()}.{group.Key}", false);
#endif
Please @ me and thanks in advance!
you should check the source/decompilation of that method if you want to know what it does
but if you want to be sure, just use the explicit ToULong. ToString could be user-facing and come with more info
Package is outside the project, and I am genuinely not even sure how to do that in nvim yet :/
thanks!
when using graphical ides, you can ctrl+click symbols to view their source (or decompiled versions)
not sure what the equivalent for nvim would be, but do consider keeping another ide handy for that if nvim doesn't give an easy way to do it
granted it could be extern'd, but won't know until you check
Just curious, why do you choose to use that (for unity dev)?
UnityCsReference is at 6.2.0b4 right now lmao
Started with vs, switched to rider, switched to linux, switched to zed, and now finally switched no nvim.
I can just use it anywhere, even when I ssh into my server, it's just way more convenient to configure one thing correctly and use it everywhere than have 5 different tools that do the same job.
On top of that, rider's "free" license is not exactly free, you can't be making money iirc.
And prob the main reason, I just like nvim binds ig(none of the integrations besides zed are anywhere close to the real thing).
Zed does have the remote thing, but that opens a whole new zed window instead of just staying in the terminal, and not to mention devs refusing to merge in half the features that have been open for 3+ years, but besides that, it was a decent editor for a while.
And prob one last thing that might explain why I like minimal editors, I just don't like all the popups etc. that get in your way.
I have autocompletions set up to appear when I press ctrl+space, but I hate them constantly being there.
Ik you can do this in other ides too, I just found it to be easier here.
fwiw vscode has a "vim mode" (and "emacs mode"), i'd hazard a guess other ides have them too. not saying to switch, just mentioning that in case it might make your life easier if you do have to use others lol
Yeah, they are pretty decent too, I used the one in rider aswell(ideavim iirc), it's just way less configurable(could be a skill issue), and it doesn't feel like a first class citizen(besides zed).
ah well i can't find it now that i mention it lol. mightve been in like, monaco or something.
idk if the fact that it can fall is normal (player movement)
oh they're extensions. i was remembering "vim mode" from coc's embedded monaco lmao...
Let's say I got an effect class. I'm trying to think how I would neatly introduce the concept of effect durations and the associated duration types (instant, seconds, infinite, etc.). Should I introduce this stuff within the effect class itself, or extend out into child classes for this?
using UnityEngine;
public abstract class Effect : ScriptableObject
{
public abstract void OnApply(EffectContext context);
}
it's normal for the physics system
if you want it to fall for your game, then it's normal for your game
if you don't want it to fall for your game, then it's not normal for your game
and if I dont want it to fall how do I make it so it doesnt
are you referring to falling down or falling over?
fallingg over
constrain x and z rotation on the rigidbody
so in the fixedupdate I just put its x and z rotation to 0?
no, there's a section called constraints on the rigidbody component
consider drawing out (on paper, on a whiteboard, in notepad, etc) the relation between this class and its users, how they interact and such
see what you need as the API for this object, see how that fits in with making conditionals vs making subclasses
ik that's pretty vague advice but it'll really depend quite a bit on what it needs to do and how you want to do it (eg where might branching decisions be?)
how do I make the mouse cursor not visible like in most first person games? solved
Hey, just one more question about this.
Which is closer logically speaking, what I did above, or this:
https://docs.unity3d.com/6000.5/Documentation/ScriptReference/EntityId.GetHashCode.html?
How would I make a variable change on a curve?
Like a certain stat that grows less the more it levels, for example: Level 1 adds 5 points, level 2 adds 4 points, level 3 adds 3 points, etc
A mathematical formula typically. But in unity you can cheat with animation curves.
Or a lookup table. Might be more suitable for integers that you want to author yourself.
I'm just trying to do the level scaling on a curve so it naturally tops out and figured having a simple formula/function that does it would be easier than having a chart of all the stats at each level 😅
Then look into unity animation curves. You can then floor/ceil/round the number to an integer.
i tried learning a few months ago but i kind of just stopped doing it, thinking about starting again
really want to do it but its so complicated lol
i get a proper setup in a week or 2 so thats nice
should i try the tutorial template thingies?
Learning what exactly? The C# programming language, Unity API or game development?
is using the id or using the hash of the id closer to using the id 🤔
What an impossibly vague question
What part of a "3d Shop" are you having trouble with coding?
And the answer can't be "all of it because I didn't try"
yeah, I was a bit fried when I asked that 🤦♂️
thanks for confirming tho
I am using a delta pointer, if I position my mouse off center of my game when i start it, why does the camera instantly snap to that position but on the second frame?
Shouldn't that be perceived as no change since that was the position of the mouse when I started the game?
using Unity.Mathematics;
using UnityEngine;
using UnityEngine.InputSystem;
public class CameraController : MonoBehaviour
{
[SerializeField] Camera Camera;
[SerializeField] CursorLockMode CursorLockMode;
[SerializeField] float MinimumPitch;
[SerializeField] float MaximumPitch;
[SerializeField] float MinimumYaw;
[SerializeField] float MaximumYaw;
[SerializeField] float Sensitivity;
private Vector2 current_mouse_xy;
private float total_pitch;
private float total_yaw;
void Start()
{
Cursor.lockState = CursorLockMode; // Locked, Confined, None
}
void Update()
{
total_pitch -= current_mouse_xy.y * Sensitivity;
total_yaw += current_mouse_xy.x * Sensitivity;
total_pitch = (MinimumPitch == MaximumPitch) && (MinimumPitch == 0) ? total_pitch : math.clamp(total_pitch, MinimumPitch, MaximumPitch);
total_yaw = (MinimumYaw == MaximumYaw) && (MinimumYaw == 0) ? total_yaw : math.clamp(total_yaw, MinimumYaw, MaximumYaw);
transform.localRotation = Quaternion.Euler(total_pitch, total_yaw, 0);
}
public void OnCameraLook(InputAction.CallbackContext mouse_input) => current_mouse_xy = mouse_input.ReadValue<Vector2>();
}
The first image is from me printing the mouse_input.performed
*I tried to use an if statement to remove every other input but they were Vector2.zero so it doesn't affect the code
When you lock the cursor that instantly warps the cursor to the center of the screen and any offset is probably interpreted as mouse delta.
Hey guys, i'm having a stroke I think xD
I'm trying to make a 2D rectangle where I can change each pixels individually with code for testing some functions of procedural generation before going 3D.
It seems I can't find any tutorials that explain how to handle pixels indivisually, and i'm sure i've seen some tutorials a couple years ealiers so I know those exists....
a texture?
anyone wanna see if my playfab login is secure or not it was taken from youtube and changed up
Hi, when I build my project my FPS are even worse than in the editor. Somehow the cams are using nearly everything. Also LogStringToConsol takes a huge piece of that, But I checked every script in the scene and non of that is calling Debug.Log repeatedly. What could cause this?
whats calling logscenetoconsole?
Where can I see that? because when I hit view I only see the DebuglogHandler.cs script or it tells me Profiler.Writebuffer
Select a frame in the chart, switch to profiler hierarchy mode, sort by cpu time, expand to the problematic call.
Take a screenshot of the whole profiler window.
yeah, thats what I wanted to show with the photo that Main Camera and Camera are taking over 70% of the total
Avoid cutting your screenshots like that. We need more context...
And avoid relying on percentages. Rely on cpu time.
So is there a way to export it? because it splits into a bunch of different smaller tasks
Export what? Can you start with providing a screenshot of the full profiler window with hierarchy visible??
Sorted by (cpu) time
so like that
Yes.
So a few things to clear up:
- you're getting stable 60 fps(aside from a few spikes).
- it seems like you have 2 cameras rendering a lot of objects.
You don't need to expand all the way down. It's enough to go down to 5ms split and maybe one call deeper.
I forgot that I got a mirror with a secon cam. But do you know why I have 130 - 160FPS in the editor while plaing but only 60-100FPS in the Build? and the spikes are the fault of a search algorithm but thats an easy fix
what resolution are you running the editor game view at?
One possible reason is resolution differences. Your editor viewport is probably way smaller than the play. Aside from that, it could be quality settings difference. Hard to say without comparing both.
Free aspect, Its around 4/5 of my 2560 x 1440 monitor
Thanks for the help. The profiler is still a bit overwhelmingwith all these taps to open.
i have a little flickering around the objects where do i post this issue for solution
If you need a better answer, share profiler data from build so that we can compare.
so i just download the unity hub but when it downloads the editor at 100% it says validating then faild to download i tried three times but still the same
Do you have enough disk space?
I like the design. I don't know enough to give a fullproof answer, but.. does this may be due to the light source angle? - actually no... do like dlich said, check in with rendering
i got 75 gb
thanks and i tried changing the direction but its still there 🙁
: / Not what I'm experienced with, I'll have to side with dlich on this one.
owk thanks
the rect transform of a UI object is being set to -9720 making it not display on screen and i can't seem to set it to 0 even with Vector2s or a Vector3 with a 0 at the end.
Only way I can stop it is changing transform.position to localPosition but then the box does not align with the mouse position
{
//transform.localPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
transform.position = Input.mousePosition;
}
public void SetAndShowTooltip(string message)
{
gameObject.SetActive(true);
textComponent.text = message;
Cursor.visible = false;
gameObject.GetComponent<RectTransform>().pivot = new Vector2(0, 1);
}```
Orthographic camera, Canvas render mode set to screen space camera
You might need to use RectTransform anchoredPosition?
@queen vale
its working the same as localPosition its no longer in the negative thousands but now its offset from the mouse 🤔
transform.position = Input.mousePosition; // ?
what anchor are you using?
middle center
wouldnt that be 0.5, 0.5
I hear you, and I'm thinking. Just not sure at the moment
thanks!
Batby, you got any ideas?
Are there any errors or anything?
Without further information, I'd look to this
if (canTurbo)
{
if (Input.GetKey(KeyCode.Space))
{
playerRb.AddForce(focalPoint.transform.forward * turboStrength * Time.deltaTime, ForceMode.Impulse);
canTurbo = false;
GameObject TurboParticle = Instantiate(turboParticlePrefab, transform.position, turboParticlePrefab.transform.rotation) as GameObject;
StartCoroutine(TurboCooldown());
}
}
}
IEnumerator TurboCooldown()
{
yield return new WaitForSeconds(turboCooldown);
Destroy(turboParticle);
canTurbo = true;
}
why does the instantiated object does not destroy() ?
what is turboParticle
oh i think i found it i am stupid
😛
oh nvm still doesnt destroy()
probably wrong but doesn't a coroutine need to return something?
yield return new waitforseconds(0.5f); kinda thing at the end?
i changed it already
you need to post up to date code for up to date advice 😛
but still doesnt work
don't quote me but, I would do it as:
IEnumerator TurboCooldown()
{
while(activeInHierachy)
{
Destroy(turboParticle);
canTurbo = true;
yield return new WaitForSeconds(turboCooldown);
}
}
: |
: | what'd i do this time
if (Input.GetKey(KeyCode.Space))
{
playerRb.AddForce(focalPoint.transform.forward * turboStrength * Time.deltaTime, ForceMode.Impulse);
canTurbo = false;
GameObject turboParticle = Instantiate(turboParticlePrefab, transform.position, turboParticlePrefab.transform.rotation) as GameObject;
StartCoroutine(TurboCooldown());
}
}
}
IEnumerator TurboCooldown()
{
yield return new WaitForSeconds(turboCooldown);
Destroy(turboParticle);
canTurbo = true;
}
this still doesnt work
so their routine is fine, but what about return at the first line of it running?
also fine
: o oh
correct, because of the GameObject type deceleration in the top code, that's a local variable to that function.
turboParticle and turboParticle are still different things here (confusing i know)
You can just do turboParticle = Instantiate(turboParticlePrefab, transform.position, turboParticlePrefab.transform.rotation);
So this is a scope issue(?)
oh i see
it says its cuz he didnt respond to UAC popup but i did everytime but it still says download also in the install help documentation they said check the logs or install in different disk i couldnt find anything in logs but installing it in different disk gives the same error and one of the guy says it happenes in newer version old one downloads fine now how do i select which version i want to download
doesn't need to be public, private would be fine. is your code not erroring and giving you red lines right now?
or can i assign arguments to the Ienumerator
no
this should be invalid code if you don't already have a turboParticle variable declared in that class
IEnumerator TurboCooldown()
{
yield return new WaitForSeconds(turboCooldown);
Destroy(turboParticle);
canTurbo = true;
}
its in the same "public class PlayerControllerX : MonoBehaviour" class if that is what you refer to?
or do you mean Ienumerator
📃 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.
is the coroutine ever started?
StartCoroutine(TurboCooldown()); - vs - StartCoroutine(TurboCooldown);
thank you i fixed it
not again ; - ; - nvm. I'm not answering anything without an IDE open lol
IEnumerator TurboCooldown()
{
GameObject turboParticle = Instantiate(turboParticlePrefab, transform.position, turboParticlePrefab.transform.rotation) as GameObject;
yield return new WaitForSeconds(turboCooldown);
Destroy(turboParticle);
canTurbo = true;
}
is this good practice? or should i use arguments or public stuff
that's fine as a solution in isolation but it's not ideal that you don't know what was happening before (no judgement it's just a pretty core thing)
yeah i just forgot that it was in a differnet scope
really simple one but does anyone know how to put text on a prefab like not with the canvas?? if that makes sense like its a child of the parent prefab i guess and moves with it
world space canvas
either on the prefab itself or on the gameobject parent the prefab spawns under
There's a world space text object in create menu -> 3D Object
thanks!
all really i think
why dosent it let me add this font??
Because it's not a TMP font asset. https://docs.unity3d.com/Packages/com.unity.textmeshpro@3.2/manual/FontAssets.html (and #📲┃ui-ux)
sure, I would appreciate it. So I removed the mirror for now and I found out that the huge spike has to do something with the Bloom or... But I am not sure. overall it is running between 100-200FPS, But is this normal in such a tiny scene? Games like GTA or Arc Raiders run in a similar frame rate (70-100 in Heigh settings)
Pretty normal, also note that the editor itself has a lot of overhead and you will get higher framerates in a build
I forgot to mention that all lights are baked
I get around 100-200 in the build.
The spike is likely something like shader or PSO compilation - something that happens once the first time the shader is used(there are ways around it, but it's a whole different story).
As for fps, as a gamedev you should start thinking in frame time(in ms) rather than fps. 100 fps is like 10 ms frames, while 200 is 5ms. 60 fps is 16.6 ms, so 60 to 100 is almost the same difference in time as between 100 and 200 fps.
And then there are optimizations.
forgot to mention that too 😅
Also, normally you want your fps to be limited to the user monitor refresh rate, which is 60 fps for majority of users.
ok, I just dont use V-sync because Its always very jittery on my monitor but I don't know why. no matter which game
Might be something with your monitor and/or gpu settings. Should check your monitor refresh rate and the fps you get when it's enabled.
Yo guys, what's up? I'm kinda new to programming and I'm having some trouble to construct my PlayerController class. I've used Claude to act like an instructor to me, so we constructed the system based on events, it works, but I'm feeling like I'm losing control of the system. What do you recommend? Keep trying to fix or start again with other architecture? the projetc until now: https://github.com/magopoligonal/Unity/tree/CombatSystem/Aprendizados/Assets/Scripts
Basico. Contribute to magopoligonal/Unity development by creating an account on GitHub.
Do you have a specific question here?
My recommendation is to not use any code Claude produces until you understand what it's doing. Otherwise you will absolutely "lose control" of it. It's a powerful tool but not super useful if you don't understand what it's doing.
Anyway this is just vague and nobody (other than an ai tool) is going to spend a lot of time looking over a whole project and making general recommendations without a specific question
Yeah, that's make sense, sorry for that haha. My main question is if it's okay work with events to pass and control data, it looks uncoupled but at the same time it's hard to control priority. For example, I'm having trouble to make a combo system. I've fixed a lot of things, but my transition between Attack02 to Attack03 is broken. It's like they can pass trough the coroutine without respecting the time window that I put on the animation event.
A proper combo system is essentially implemented as a state machine. Any input should be fed into the state machine, typically into the current state, which should decide what to do with it
Can anyone tell me why my VS turned into all these whacky colors over night?
I'm still not a OOP guy (started with C ), you recommend to use interface and stuff? I've seen some tutorials on that I think but it feels scary at the first glance ;-
It used to be the normal colors of light blue/cyan stuff. Why all this red/orange?
Interfaces are a tool. I recommend using that tool in the appropriate circumstances. It's not clear to me the context in which you're asking
pretty sure they just updated the software and there's new default colors. I thnk I saw some other people talking about it the past couple of days. I don't personally use VS though
AFAIK I you can customize the colors and the old theme probably still exists somewhere
Wait so they updated the software and changed all the colors from what they were for the last 10 years?
Is this for real
ohh okay so how do i fix that?
Like I said I don't use Visual Studio, so I don't know. Just basing this off what I've seen in this discord casually over the last few days
maybe just ignore mouse delta input for one frame after locking the cursor
Thanks bro, much easier on the eyes
okay, do i need to check that every time i tab in?
check what?
the frames the mouse is being locked
the code would be pretty simple.
E.g.:
bool ignoreMouseDelta;
void LockCursor() {
Cursor.lockState = CursorLockMode;
ignoreMouseDelta = true;
}
public void OnCameraLook(InputAction.CallbackContext mouse_input) {
if (ignoreMouseDelta) {
current_mouse_xy = Vector2.zero;
ignoreMouseDelta = false;
}
else {
current_mouse_xy = mouse_input.ReadValue<Vector2>();
}
}```
okay thanks!!
wait
by the way
the way you're handling OnCameraLook isn't ideal anyway
It actually looks really buggy
Pretty sure OnCameraLook is only going to run when the mouse is actually moving
Are you actually getting calls to OnCameraLook when the input is zero?
If not this code is just going to keep spinning you forever
I'm trying to make a game where everything thats within a 360 degree view of the player is frozen in time.
I think i have an approach to work out whether an object is in view, but I thought I'd check in case its impossible/stupid. The big constraint is that if just one pixel of the object is on screen, it should be frozen.
My approach is this:
Write a shader that makes the color of each pixel the objectID it hits
Render a cubemap from the playercamera with that shader with a pretty low resolution, then iterate over the pixels, and say the object should be frozen that frame if it's in there
Any advice?
i don't get how these two statements don't conflict
A "360 degree view" is, like, everywhere
Oh i mean like, if you consider the "screen" to be that 360 degree view
Walls will block the view
My understanding was that unity's occlusion culling would be too approximate - I need like, super consistent behaviour otherwise it'll feel cheap.
If I'm wrong and its super exact though, I'll use that
i don't think any solution is gonna be perfect for you off the bat
maybe you'll need a little timer or something aswell idk
you'll have to play around abit
def. probably not that pixel shader route
Thats just too slow I'm guessing? From iterating over a ton of pixels on the cpu every frame
too slow and probably not a very accurate way either tbh
either those camera functions or manual raycasting / physics related stuff is probably your route
Do you know if OnBecameVisible is gonna be inaccurate on only one side? Eg. if its actually visible, its visible all the time according to that function, or is it that if its invisible according to the function, its actually invisible all the time. Because i could use that to chop down the things to check a little
If there was an easy and fast solution to do mathematically perfect occlusion culling, unity and every other game engine out there would use it
i dont know what you mean by this
I'm willing to take some performance hit, this is going to be one of the only features in the game and the levels will be small and barely decorated
I don't know if this is the right place but... I have been wanting to make a video game but programming in C# is the only thing standing in my way. I have been using Unity for about 4 months now (following tutorials) but whenever I try to make my own game stuff falls apart until I inevitably delete the project. Where can I go to learn all the physics and C# related stuff so I can actually code my games?
Check the pins here
also
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Visual aid because I'm bad at explaining things.
If you imagine whether you are in view or not is on that scale.
The black scale is the truth of whether you are in view, if you are to the left of the bar, you arent in view, and if you are on the right, you are in view.
The red scales are possibilities for what unity could be telling me - In the top case for example, if you are past the red bar, you know for a fact that the player can see it, but if you are to the left of it, it could be that you cant see it, but unity says you can.
Like a "A implies B, but B does not imply A", but in this case its "Unity says object became visible => object is actually visible, but object is actually visible =/> unity says object became visible"
It could of course be neither, and its just completely approximate
the two unity calls are consistent in how they are ran
they are either consistently "wrong" or "right" depending on what you want out of them
Also, if im not mistaken, occlusion maps are baked? So using OnBecameVisible wouldn't work with using objects to block view of other objects
these calls are not related to occlusion culling afaik
Oh wait for real? Ok I'm gonna at least give it a try then, thanks
The problem is that implementing an accurate occlusion culling system is very hard even not taking performance into account. I would like to know why even one visible pixel needs to freeze the object? Why it needs to be that accurate? Would that then mean different game resolutions would result in different results? What does visible pixel even mean for something that is behind the camera and therefore not rendered? Is object being just slightly behind other object and it being registered as visible as bad as the other way around?
It's just sort of nice to have it be completely in line with the rule of the game universe. The player would go for the entire game without seeing a single little thing move, so having it not be perfect would hurt a little. I would be willing to compromise on that last point though, if its just barely not visible, its fine for it to be counted as visible. Also a visible pixel would just be a visible pixel on the 360 degree view, like eg. if you put one camera facing up down north east south west.
Thanks for your help, however, I started one of the programming paths a while back but when I implement what I learned it's extremely jittery and doesn't work as well. I think it might be outdated
More likely that you missed some part totally or made some little mistake
I think the learning pathways provide couple different unity versions to choose from. I would be surprised if the newest is outdated
Well, I can assure you I didn't miss anything it's just that they want you to use transform.Translate() which is more of teleporting the player. This causes it to be more jittery than a rigid body force
If anything, moving via transform should be much less jittery than anything with physics. Unless you have a rigidbody on the same object fighting against the translate. If the object has a rigidbody, then moving via transform isn't great, don't know how any of that implies anything being outdated
It uses the old input system, and they actually want you to add a rigidbody for physics!
sounds good?
how else are you planning to use the built in physics?
unless you mean they want you to both add the rigidbody and use .translate?
Yes, and it actually isn't that bad in the tutorial project but I make my own project with the same scripts or slightly changed so it works and BOOM lag and jitter
what needed changes so it works
sounds like a problem to fix not a reason to quit
Look, all I want is to learn C# do I can make my games. I really don't want to argue or get into it with anybody right now
no one cares to argue
figuring out what you did wrong is the first step to doing it right
if you have problems with the suggested answer people gave you
perhaps look online
Normally I go to ChatGPT to find tutorials online but that screwed up my past few projects and gave me horrible code. I wanted to talk to humans so I can actually find an educator or something
almost all 1:1 educators would be a paid situation
here we are happy to link to learning resources and help teach and troubleshoot specific pieces of knowledge
Well guess I am alone here, if I have any problems I will bring them here and hope someone can help 🙏
we are always happy to assist with projects and individual problems
Unless it's Gorilla Tag
i don't think those ones count as individual problems
i took a peek at their discord... and yeah, most people are sending those people here to get help with their projects
or to find collaborators
quite litterally just making it someone elses problem lol
oh dear
To elaborate on the point about pixels beyond the screen: let's say you have an object from which only one third of a pixel worth of corner pokes out from behind other object. If you render that view, it will depend on the exact alignment (and whether MSAA is enabled perhaps) whether that object has 1 or 0 pixels visible. Unless you use some exact mathematical solution (which is probably really hard and slow), even rendering the scene from all sides and counting the pixels would not give 100% accurate results.
One more problem that you probably haven't thought of, let's say you have an object A which moves really fast, let's say 10 units a second. Rendering at 100fps, that would mean movement of 0.1 units every frame. If A is coming from behind other object B but is this frame still barely behind B, you would allow A to move. That would cause almost 0.1 units of A becoming visible from behind B which would seem like movement to the player albeit only for one frame (then it would be visible and stop). Add a moving camera to the mix and it will probably become a nightmarish task to perfectly prevent this problem from occurring while maintaining any form of acceptable performance whether that means 1 or 100fps.
All I'm trying to say is that a perfect occlusion culling system like this is really really hard to implement if it needs to be perfect down to a single pixel or even more. At that point we are in a territory way beyond beginner code
In terms of that exact pixel alignment problem, i am fine if we very slightly allow some leeway on the side of freezing objects that are barely not in view.
And i have thought about that problem of fast moving objects, and my proposed solution is for any moving object (the only moving object will be a simple cube) to have a "ghost" version of it, which is one frame ahead, and the actually visible version which follows it
Even with that ghost approach, you would have a lot of edge cases especially if both A and B would be moving
This is true... Well, this is pretty much the only feature I need to get my game working, so I'll probably just spend a long time experimenting and find a solution I'm happy with. The idea is too good to not make 😂 . Thanks for your input though, its been helpful 👍
If I was you, I would start from some approximation like the occlusion methods unity provides and custom approximations usign raycasts and such
Guys what to do with the void start function in this code i have no use for it
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BusScript : MonoBehaviour
{
public float speed = 5f;
void Start()
{
}
void Update()
{
transform.Translate(Vector3.forward * speed * Time.deltaTime);
}
}
Just DM me
this dude did not read the rules
!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.
wanting ppl to slide in DMs for such a simple answer is mind boggling lol
Feed it to your children
!Learn Start with coding tutorials or better with Unity courses, to not ask elementary questions here.
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Whatever you want
If it only included the visible viewport, I would also consider rendering the ghost only scene to a render texture with object IDs and then reading those IDs in compute shader but it being a 360 makes it that much harder to implement fast enough. Reading back from the GPU memory can also introduce delay of multiple frames so even that is probably not good enough for the viewport only solution
i dont think its 360
If its not clear what 360 degrees means, i mean if you can draw an uninterupted line from the player camera position to some point on the object, it should be frozen
it is clear what 360 degrees means
it's just not that
hence why people got confused
if it is legit just 360
im still honestly confused as to what 360 is supposed to mean here
then thats just raycasts
cuz shaders could not work there at all
since it would include stuff not in screen
When i said 360 i was thinking in my head of 360 degree videos, but obviously what i had in my head didnt translate, sorry guys 😭 . The problem i had with raycasts was you have to pick sample points on the object, and you would need a lot to make it actually accurate, to the point that I was thinking thats pretty much what happens in rendering and that could be related to a solution
I could limit the actual amount i have to render, by only taking small snapshots of the feasible objects bounding box or something, but if theres gonna be a few frames delay communicating with the gpu, thats a dealbreaker huh.
Bunch of raycasts is probably your best bet
Can somebody help, so All of my animations play in the beginning of my game, but after the game restarts and i´m in the main menu, if i press play it just doesn´t play the animations anymore, only the idle animation, from the main menu, even altough i made idle to Jog animation with speed greater than 0 and also no animation plays after i restart the game besides the idle animation from the main menu, like the death animation doesn´t play or the jump animation so literally nothing, this is my script for my character:
please post code properly
!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.
try checking the animator window and see if the parameters are as expected
you should not be using transform.Translate if you have an rb
nothing happens so at first everything is fine but after the restart even if the idle animation plays, in the animator tab nothing happens no loading bar
have you selected the relevant object
do fix this too
I´m trying to use [SerialiseField] Transform cameraTramsform for my CameraController but nothing is popping up in the inspector.. What am I doing wrong??
Do you have any compile errors
can´t see any
have you saved and recompiled
nope and I´m a dummie wdum by "recompiling"
When you make changes in your code it needs to be compiled for the changes to apply
this typically happens when you save a script of any kind, it auto recompiles inside of unity
if you didnt save, or you didnt manually recompile, then the changes wont apply
yeah okay of course I save my files
then are you positive its the correct script thats attached?
if you right click the script in inspector and hit edit script
what opens up
wait did you spell it like this verbatim?
100% the same script
because its also "Serialize" not with an s
you confirmed this with the way i told you to do it?
by hitting "edit script" in the inspector?
i did
alright then the next logical step is for you to send the script here, and screenshot the inspector and show it to us
!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.
Then use a different one
also its working fine for me
a powerful website for storing and sharing text and code snippets. completely free and open source.
Where are you looking to see if there are compile errors?
Console I guess
Make sure you're looking at the Unity console
I am
also in general dont send code as .txt files
Can you send us a screenshot of the console?
some platforms do not embed those
this, had to start the game, didn´t do it before (my mistake sry)
this isn't a compile error
this is a runtime error
this won't cause the field not to show up. Either your code file hasn't been saved or Unity hasn't refreshed it after it did. You can force a refresh with ctrl+r. By default it should refresh automatically though, unless you disabled automatic asset refreshes.
ok it suddenly showed up thanks a lot
My guess is you have automatic asset refreshing disabled.
where to turn it back on?
also a bit unrelated to your issue... but where do you actually call your mouseinput function
I will.. in Update() but I won´t before I can actually use my Inputs
Edit -> preferences -> Asset Pipeline
thks
Sorry i´m a bit late, no it doesn´t fix it, i think it doesn´t really changes much, but i noticed something, so my fault, after the game restarts and i select the player, in the animation window it shows the exact same as before the game restart, so for example in the main menu its loading the idle animation and there is this loading bar in the animator, also if i hit play, the walk animation also has a loading bar, which means all the conditions work and the animations should play, but somehow they doesn´t
how would i go about animating a single character at a time with TextMeshProUGUI?
{
float currentDelay = 0;
textHolder.color = textColor;
if (i < secondColorRangeMax && i > secondColorRangeMin)
{ textHolder.text += "<color=#" + ColorUtility.ToHtmlStringRGB(secondTextColor) + ">" + input[i] + "</color>"; currentDelay = delay2; }
else
{ textHolder.text += input[i]; currentDelay = delay; }
//play bounce anim
SoundManager.instance.PlaySound(sound);
yield return new WaitForSeconds(currentDelay);
}```
this is what i have for a simple dialogue system so far, but when each character gets added i want it to play small bounce animation. any help would be appreciated
Look at some tweening libraries, not sure what's the recommended one these days but tweening can be used for simple code-driven animations
Or just use the animator if you want to
its all good i got it workin 👍
i'm in a game jam with not much time left and i have this charged attack that impulses if you hold the button and release it how can i make an effect so it looks like it's charging
yeah
ask in #✨┃vfx-and-particles
ok thx
hi guys so m jus asking does anyone jnow how to use a unity asset package ?
drag into the unity editor while open and it will let you import its contents
i did imported the content u see but i couldn't g=quiet figure out how to use it
Once "imported" its in your projects assets can be used as they instruct
ok umm u see what this asset file seems to have is many texture shader files my goal is to use that in order to make a working ocean or such but when i searched about it it kinda looks too much complicated since it depends on some frequencies etc stuff that m really not interested to hear can anyone help ?
so wait lol
you arent interested in trying to understand how the asset works
but we are supposed to be.... so we can help you get it working?
that doesnt seem quite fair lol
m not asking u to know m just asking if u already know
since m just a begginer lol
already know what?
k have anyone ever used the SUIMONO Water System asset pack ?
Unlikely. You should see what documentation and support the asset provides
u mean among the files it has ?
k thx
im using classes like these in my game GCR for all game and LevelContentRoot for Levels. What pattern to use, if i have to give PlayerInput reference to player instance?
Have this spawn and init the player? Or the player is meerly given an input action map reference/name to use
player can be spawned, but LCR holds reference to player
Then whatever loads your level can be given initialisation data in some from this class?
When i had level loaders like this that would init the scene and pass in all important references
my levels are prefabs. I load scene which has basic data and LCR, and only then level layout prefab created
So? If you are writing the code to do this work then you can control the process
I could pass input reference from GCR to LCR, but how?
When you load the scene/prefab you get a component by some base type or interface and call a function to "connect" them
With scene loading we can get root game objects if you want to avoid a Find by type
You can also go the route of a dependency injection system (custom or pre made)
this doesnt count as dependency injection?
It could but I have already explained how it can be done manually
The alternative is some static manager that provides access to common data/references but comes with its own downsides
i could make them from abstract class, which has static value with reference. It wont work right?
for me it is.
You just need a hierachy of "control"
But in this specific instance, player input just maps to input actions in an asset so this is easy to re setup elsewhere
But in general a hierarchy of control and design such as mvc can help produce cleaner code.
you want to tell me that i dont need playerInput class?
If you read the documentation on what it does, its just helping you use an input action map and actions
But understanding design to move data where you want is still good to learn
sorry for the late response
yeah it is
im getting it even with my mouse disconnected
however it is Vector2.zero
your ide is not configured
i feel like we've been over this...
!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
Hello,
I was curious if anyone had any recommendations for learning game architecture/design as the scale increases.
I'm relatively okay when it comes to something small, but as the scope increases... I want to make something more.... modular/expandable?
Idk, something went wrong, but most of time it works
👌 Will check it out, thank you.
Maybe on same topic, how to structure folders?
yo whats up chat
how do I unlock the cursor from the game/window? everytime I run my game the cursor enters the game I'm making something similar to desktopmate so it has to be free
I have disabled all character controlling components and I'm using code like this aswell but its not working:
void OnApplicationFocus(bool hasFocus){
Cursor.lockState = CursorLockMode.None;
Cursor.visible = true;
}
Place a log and see if this method ever runs.
It's part of a bigger script, the rest of it is running so this one should too
assumptions are death
Should. You need to test if the statement runs.
Alright give me a moment to debug it
it looks like it is being called, I'm not sure how unity handles it so im not sure where else to check
Can you show where you placed the log?
void OnApplicationFocus(bool hasFocus)
{
Cursor.lockState = CursorLockMode.None;
Cursor.visible = true;
Debug.Log("Cursor check succsesful!");
}
!code
How to post code btw for future references
There's no command called
code how.
!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.
its also being called every single frame so theoretically it shouldn't conflict with anything else
also gotcha, I joined like 3 mins ago lol
or rather even if it conflicts this one would come ontop
Are you locking the cursor anywhere?
not me, I'm using kyle prefab, I disabled all his components though
the game is on screen right now, when I click it the mouse disappears, idk if this screenshot could help locate the problem
Try this:cs void OnApplicationFocus(bool hasFocus) { Debug.Log($"Before: Lock state is {Cursor.lockState}"); Cursor.lockState = CursorLockMode.None; Cursor.visible = true; Debug.Log($"After: Lock state is {Cursor.lockState}"); }
I'm assuming none means it should be free right?
The cursor is by default unlocked. You just have to find the component that keeps locking it, not much else you can do
I'm very new to unity, this is my first project, do any of the defaults do that or should i only look at the stuff I imported like kyle?
Yeah, you're trying to unlock it multiple times but you've got something locking it prior to every application focus call
Disable everything in the scene, then enable them one by one until the cursor becomes locked. Then you know which one is doing it
yeah thats probably the best approach since the default is the mouse being free; should be pretty easy to find the source. thanks for the feedback everyone
Can someone help me make a text scroll view in unity?
I followed every step and went back over and over again and the list is not scrolling
Like it's restricted I can't drag down
If ugui you need to use layout groups or content size fitter to have the text grow it's rect transform
what instructions are you following?
So basically with buttons it works
But with a big text is not working
I'm trying to make a log scrollview
And I ended up making prefabs of log entries
It worked
no, why do you ask?
I'm guessing that the content area doesn't know how much space the text needs
idk when i was working on C/SDL stuff got slower when i used for loops for certain things, so i assumed using for loops in update would slow things down
the golden rule with uGUI is that every element should either:
- ask for the space it needs directly
- use a layout group to ask its children for how much space they need
trying to learn correct coding practice for unity
so, for example, this would work
- Content <-- vertical layout group, content size fitter
- Log Item <-- vertical layout group
- Text <-- TextMeshProUGUI component (this asks for the space it needs)
- Log Item <-- vertical layout group
i mean, if you use loops, you're doing more stuff, so it will, indeed, get slower
yeah its why im wondering if for loops are generally avoided unless you absolutely need them
i mean, you use them when you need to do something many times
and you don't use them when you don't
yourt question sounds confusing to me; you're asking if you should put gas in your car
it costs money, but the car isn't very useful if it can't move :p
i mean there is more than 1 way of implementing things, is what im saying lol
sometimes you can use a for loop, or you can look into whatever your implementing and find a more complex solution that saves time
so what im asking is: are for loops generally avoided if you can find another implementation, or is it fine just being hacky and using for loops
not sure how this is hard to understand
a for loop is simply a way to execute a statement many times; there is nothing intrinsically "hacky" about this
Yeah it's much safer with multiple entities
lol
There might be a solution for that but I can't think of it
its like doubling an item, you can *=2 or you can just bit shift left
bit shifting left is 1 operatoin
*=2 is many
you're going to need to provide an example of what you'd be "replacing" a loop with here
or a more unity example and the reason why im asking it, i was about to array all my text for a certina use function and use a for loop instead of using a OnTriggerEnter with a trigger collider. Obviously the for loop would have still worked, but the ontriggerenter is cleaner
would it have been fine using a for loop, or do i avoid it, like ive been asking at the start
i mean, yes, that is obviously better
but that's borderline-tautological: it's obviously not good to do something like
for (int idx = 0; idx < 1000; ++idx) {
Debug.Log("Doing this for no reason.");
}
it's not, its multiple methods for the same implementation
this is just redundant code
I guess you're asking about manually checking for a condition vs. relying on the physics system
and yes, using physics is often more efficient (and easier to reason about)
especially when you have a large number of possible interactions
(i'm unclear what you'd even be doing in that for loop)
was the idea to check if you're close enough to each interactable object?
checking if the player is near the text to make it visible
Ah, okay, now this makes a lot more sense
You should have led with that :p
This comes up pretty frequently
note that checking a few distances every frame is extremely cheap
but I think the big win isn't that it performs better
it's easier to reason about
you don't need to have a giant list of every interactable object; you just need to detect that you've entered a trigger collider and see if it's part of something you can interact with
yeah still getting used to unity/c# syntax
didnt even know ontriggerenter existed
gonna hate my life when i get to OOP
https://unity.huh.how/physics-messages has some useful information about physics messages
reason why i learned C lol
there are a few incantations to remember
(e.g. that trigger messages require at least one of the two objects to be part of a rigidbody)
A collider without a rigidbody is presumed to be "static"
it doesn't move
there'd be no point in checking for collisions between them
are interfaces the same as header files?
like assume you could make a header file that just includes all the files in your project with that specific method
its basically saying hey if this interface is mentioned in the class, it probably has the methods mentioned inside of the interface
no
they aren't really comparable at all
how
they're completely separate concepts
how
have you like, googled what interfaces are and what they do
lmao
some level of prior research is expected here
i mean bro you literally never give any info whatsoever this is the 2nd time now
my experience with c is super shit but the difference here is that header files point to something (no plural) that exists, no?
do you want me to just give a full description of a header file and a full description of an interface and show that they don't overlap?
where-as interfaces exist as a kinda barebones promise of what will exist for whatever implements them, which could be multiple different interpretations
i think you can have a method in a header file that doesn't exist, you are just expected to have that method
cool. that concept just doesn't apply to interfaces at all
because interfaces don't have methods, they declare methods
they say what needs to exist
that they can be compared..?
you can compare apples and oranges, of course
there is an extremely tenuous connection between the two concepts
ah yes, "header files do X while interfaces do Y which are somewhat tangentially related, so they're comparable"
header files tell another file hey this method exists, you can use it
from my understanding interfaces do the same thing as long as the method actually exists, and its universal
this is not correct
ok? i'd say interfaces don't really do that
an interface is a type
e.g.
public interface Foo {
public void Bar();
}
this declares a type namd Foo
if you implement this interface, you must implement a method with a matching type signature
The point of a C header file is to forward-declare functions so that the compiler can be aware of them before the implementation is provided (whether that be through a source file or by a library you link to)
im just trying to find a way my brain can link the dots together thats all, and using C as a comparison
cause this class/OOP stuff is new to me
I guess that both of these say "this function exists", but they do so in completely disjoint ways
"interface" just as a general english term just means a surface where 2 things meet
interface as in the c# keyword/type means you declare a generic surface that declares how 2 things can interact, but not in what way
when you create something that should be able to interact in a specific way, you use an interface to declare that and also let the compiler verify that it's correct
I would not suggest doing this.
You're going to infer things that don't really exist
if you're absolutely looking for links, then interfaces and header files serve similar roles for libraries, because they're used to achieve the same goal, declaring an API (though, for different levels of structures)
but that's not really relevant anywhere else you'd use interfaces
so an interface:
- universally tells every script, these methods exist
- these methods can only exist if the class includes the interface
- the class MUST use the methods if it includes the interface
- this allows every script to call these methods and assume the other script has it, and if it returns null, we know it doesnt
interfaces work on types, not files. if you want to draw parallels to C then consider them as guarantees of struct function pointers existing that the compiler can check i guess lol
these methods can only exist if the class includes the interface
no
the class MUST use the methods if it includes the interface
must declare
this allows every script to call these methods and assume the other script has it, and if it returns null, we know it doesnt
if what returns null?
getting the interface component
that's not a thing in c#
components are a unity thing
universally tells every script, these methods exist
c# doesn't really work on scripts. it works on classes/types
alright man can someone else help
@neon sable are you familiar with c++?
no
i would suggest reading the C# documentation
c++ has a concept called "requirements" that's pretty similar to interfaces
none of what he is saying is wrong
you're trying to look for "interfaces are headers except X", but the reality is that the list of exceptions is pretty much everything about them.
we're confused by your insistence on doing something that we've already told you does not make sense
by making the c comparison you implied some background knowledge that is needed to try and explain the differences (imo)
ur explaining it in a way thats giving off huge ego dump
but thats expected by devs
lol
how would you like me to explain it then
thats all in your head man honestly
dont worry
i literally just directly answered your questions
...because you've already made up your mind and refuse to accept the answers you don't like?
correct
not ego dump though
its not
where is the ego
Correct, it is not
literally in the unity discord
i literally just stated facts
This is a completely reasonable response
you asked. i answered
you asked why they are different, Chris is being very explicit in your wording because your giving off the impression you want that
the gaslight is crazy
those little nitpicks aren't digs at you
look how they answer questoins in the SDL discord
it matters
using a method and declaring a method are two very different things
scripts vs classes (and vs instances of classes) are very different things
c# casting and unity components are very different things
it's not being pointed out to dunk
you said this was ego, so i got the impression that you didn't understand my answers. i'm giving clarification
it's your choice to read that as further ego if you want
i think that says more about you than it does about me
Correct.
its very clearly obvious im new to c# terminology, and ur taking every thing i say is literal
right, so we're telling you now, early on
programming is literal
none of this is personal
This is a waste of time.
yes, we try to be helpful
it is, please just stop and allow someone with patience and the ability to learn new people concepts
we're not gonna sugarcoat it and say you're totally right on the comparison
we're gonna give you the truth
im not happy with your responses, i want someone who knows how to teach someone to understand how it works
A majority of the people here would have given the exact same answer, if you aren't comfortable with that this isn't the place for you
telling me that scripts and classes are 2 different things, i dont care about the terminology right now, that is automatic and i will learn it as i go along
i want to learn the concept
we do, but you've wasted our time complaining about us
the irony of saying im nitpicking
whiel you guys nitpick at specific things im saying
you need to care to learn the thing your asking to learn
i already did try to explain what interfaces were?#💻┃code-beginner message
i literally do not need to know the exact terminology right now
i also explained the concept and advised why you shouldn't try to relate interfaces to C headers
no dev does at the start
What even is the question?
i just need to knwo the concept
you literally don't know how interfaces work so no you don't literally know what you do and dont need to know
but knowing it really helps in communication and further research
so we're trying to start you off on the right foot here
script vs class is very important when you yourself brought up the header (which is closer to a script based comparison) comparison
indeed, where you care about specific files
#💻┃code-beginner message start of discussion
C# does not care about specific files
you do not "include" files, and it lacks the preprocessor macros of C
What does header files even have to do with C# and Unity? If this is a general coding question, it's not really appropriate here.
If you want to dive into those things, at least make it a thread.
indeed. I consider terminology to be very important
ok, then discard notions about header files and scripts entirely.
interface declarations say, this thing <interface name>, can do these things <methods>
anything that says it's an <interface name> must be able to do these <methods>, and thus anything else can use that thing as if it were an <interface name>
im trying to understand a concept? what do u mean
In the context of Unity?
when I TA'd a C++ class, I always made sure to use very accurate language
yes
they wanted to make a comparison that would make their question easier but they don't understand that it makes the question way harder. then they threw a hissyfit when they got given a equally more complicated answer
that doesn't make it "context of unity"
Okay, so in the context of Unity there is no header files.
they know